调用非static方法

java 的静态调用:

public class hhj{
    public static void main(String[] args ) {
        int b = getValue(2);
        System.out.println(b);
    }
    public static int getValue(int i) {

        int result = 0;

        switch (i) {

            case 1:

                result = result + i;

            case 2:

                result = result + i * 2;

            case 3:

                result = result + i * 3;

        }
        return result;
    }
}

注意这里面的b是直接赋值的类似于C语言中函数的使用;
但是注意注意注意 调用的方法必须是静态的;什么是静态的?

public static int getValue(int i){
}

就是要在public后加static
在这里插入图片描述
如果不加,类似C语言使用会报错:
在这里插入图片描述
在方法int getValue(int i)的前面加上static 就可以解决了;

问:
类中自定义非static方法,代码放在该方法内;main方法中调用上述非static方法 怎么办?

public class hhj{
    public static void main(String[] args ) {
        int b = new hhj().getValue(2);//类的引用,不能引入 不加 hhj(). 而直接引用 getValue(),也不能不创建new;
        System.out.println(b);
    }
    public  int getValue(int i) {
        int result = 0;
        switch (i) {
            case 1:
                result = result + i;
            case 2:
                result = result + i * 2;
            case 3:
                result = result + i * 3;
        }
        return result;
    }
}

方法的定义可以在主函数的上方,也可以在主函数的下方;
一个类中后面如果多加了一个 } ,报错:
在这里插入图片描述
java中的八进制是前面加0;不能用int a= 078;
会报错;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

海波东

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值