方法的调用(java)

方法的调用(java)

首先,java中的调用方法有三种:

1.静态的方法

2.非静态的方法

3.方法之间的调用

静态的方法

通过类名+方法名的方式实现

public static void main(String[] args) {
        int a=1,b=2;
        int s=Demo2.add(a,b);
        System.out.println(s);
    }
    public static int add(int a,int b){
        return a>b?a:b;
    }
非静态的方法
public static void main(String[] args) {
    int a=1,b=2;
    Demo1 demo1=new Demo1();
    int s= demo1.add(a,b);//调用非static类要将类实例化,即new一个对象,否则在方法中加static,用非静态方法
    System.out.println(s);
}
public int add(int a,int b){
    return a>b?a:b;
}
方法之间的调用(在方法内部调用其他的方法)
方法在同一类

静态方法直接调用:

    public static void main(String[] args) {
        int a=1,b=3;
        add2(a,b);
    }
    public static void add2(int a,int b) {
        a=a*b;
        b=a+3;
        add3(a,b);
    }

    public static void add3(int a,int b) {
        System.out.println(a+b);
    }

静态方法调用同一类中的非静态方法,就必须通过对象来调用。

在同一类中,非静态方法可以直接调用静态方法与非静态方法。

public static void main(String[] args) {
    int a=1,b=3;
    Demo3 demo3=new Demo3();
    demo3.add2(a,b);
}
public void add2(int a,int b) {
    a=a*b;
    b=a+3;
    add3(a,b);
}
public void add3(int a,int b) {
    System.out.println(a+b);
}

如果不在一个类当中,静态方法调用其他类中的静态方法,必须通过类名+静态方法调用。

如果在不同类当中,静态方法调用其他类的非静态方法,需要导入该类中的包,以及通过创建对象调用。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值