回顾方法的调用

回顾方法的调用

静态与非静态

当一个方法为静态(static修饰符)时,如下所示

package OOP;

public static class Student {

    public void say(){
        System.out.println("兄弟们有狗!");
    }

}

调用方法为直接调用:

package OOP;

public class Demon2 {
    public static void main(String[] args) {
        
     //Student类中的say()方法
        Student.say();
        
    }
}

当方法为非静态(没有static修饰符)时,调用方法如下:

package OOP;

public class Demon2 {
    public static void main(String[] args) {
        //非静态方法的调用
        //对象类型  对象名   =  new  对象值
        Student student = new Student();
        student.say();
        /*当Student类中的say()方法为非静态时无法Student.say()调用
        需要通过以上步骤new一个Student对象,名为student,再student.say()调用
         */

    }
}

需要先new出这个student这个类,再调用student.say()。


package OOP;

import sun.security.mscapi.CPublicKey;

public class Demon3 {
    public static void main(String[] args) {

    }
    //static 是和类一起加载的
    public static void a(){
        
    }
    //类实例化(new) 之后才存在的
    public void b(){
        
    }
}

由于注释中的原因,静态方法a不能够调用方法b,因为在a加载时,方法b不存在,无法调用不存在的方法。

形参和实参

package OOP;

public class Demon4 {
    public static void main(String[] args) {
        Demon4 demon4 = new Demon4();
        int add = demon4.add(1,2);//实参
        System.out.println(add);
    }

                 //此处ab为形参,只起占位作用
    public int add(int a ,int b){
        int sum = a+b;
        return sum;
    }
}

实际参数要与形式参数相对应。

值传递

package OOP;

public class Demon5 {
    public static void main(String[] args) {
        int a = 1;
        System.out.println(a); //结果为1
        Demon5.change(1);
        System.out.println(a); //结果为1

    }
    public static void change(int a){
        a=10;
    }
}

方法change没有返回值,main中只是把a=1传给了change方法中的a,走了一遍change,但是主程序中的a并没有变化,Demon5.change(1);只是传递给别人一个值,a本身没有变化。

posted @ 2020-11-06 11:08  SshadowHeart  阅读(52)  评论(0)    收藏  举报