Day04-概念/方法定义/方法调用

面向对象

什么是面向对象

回顾方法的定义

package com.oop.demo1;

import java.io.IOException;

//Demo01 类
public class Demo01 {
    //main方法
    public static void main(String[] args) {

    }


    /*
    修饰符    返回值类型   方法名(...){
        //方法体
        return 返回值;
    }
     */

    //return 结束方法,返回一个结果!
    public String sayHello(){
        return "hello,world";
    }

    public void hello(){
        return;
    }

    public int max(int a ,int b){
        return a>b ?a :b;//三元运算符!
    }


    //之前学的数组下标越界  :Arrayindexoutofbounds


    //异常
    public void readFile(String file) throws IOException{

    }

}

回顾方法的调用

静态方法和非静态方法

package com.oop.demo1;

public class Demo02 {

    public static void main(String[] args) {

        //静态方法 static 类名.方法名调用该方法
        Student.say();

        //非静态方法
        //实例化这个类 new
        //对象类型  对象名字  = 对象值;
        Student student = new Student();

        student.say2();

    }


    //写一个新方法时可以把上面方法先折起来
    //static是和类一起加载的
    public static void a(){
        //b();//所以一个存在的调用一个不存在的会报错,要么都加static,要么都不加
    }

    //类实例化之后(对象创建之后)才存在
    public void b(){

    }

}

形参和实参

package com.oop.demo1;

public class Demo03 {

    public static void main(String[] args) {
        //调用这个方法,有两种方式,要么new一个对象调用,要么将下面方法改为static,类名.方法名调用
        //实际参数和形式参数的类型要对应!
        int add = Demo03.add(1, 2);//实参
        System.out.println(add);

    }

    public static int add(int a,int b){
        return a+b;
    }
}

值传递

package com.oop.demo1;

//值传递
public class Demo04 {

    public static void main(String[] args) {
        int a = 1;
        System.out.println(a);//1

        Demo04.change(a);

        System.out.println(a);//1
        //因为返回值为空,相当于把a=1传给方法中的a,然后把代码走完又回到主方法,并没有返回值,此时a还是1
    }

    //返回值为空
    public static void change(int a){
        a = 10;
    }
}

引用传递

package com.oop.demo1;
//引用传递: 对象,本质还是值传递
//对象  内存!
public class Demo05 {
    public static void main(String[] args) {
        Person person = new Person();
        System.out.println(person.name);//null

        Demo05.change(person);
        System.out.println(person.name);//秦疆
    }

    public static void change(Person person){
        //person是一个对象:指向的是 --->Person person = new Person();这是一个具体的人们,可以改变属性!
        person.name = "秦疆";
    }

}

//定义了一个Person类,有一个属性:name
class Person{
    String name;//null
}
posted @ 2021-03-31 11:12  JwStudy  阅读(55)  评论(0)    收藏  举报