java静态方法和实例方法的区别

静态方法(方法前冠以static)和实例方法(前面未冠以static)的区别 
调用静态方法或说类方法时,可以使用类名做前缀,也可以使用某一个具体的对象名;通常使用类名。
static方法只能处理static域或静态方法。实例方法可以访问实例域, 静态域或静态方法, 记住都行。

class StaticTest {
    static int a = 4;
    static int b = 9;
    static void call() {
        /*下一句是错误的,因为静态的不能调用实例的方法。*/
        //callins();
        System.out.println("a = " + a+"马克-to-win"+Test.c);//静态方法可以访问静态属性
    }
    void callins() {
        call();
        System.out.println("a = " + a+"实例马克-to-win"+Test.c);//静态方法可以访问静态属性
    }
}
public class Test {
    static int c = 43;
    public static void main(String args[]) {
/*刚运行到这一步时,debug观察,StaticTest.a的值就等于4,Test.c的值就等于43,
 说明系统在我们的程序一开始时,就会给所有的类变量赋值。如果是对象参考, 就是null,
 见photoshop的例子*/    
        StaticTest se =new StaticTest();
        System.out.println("开始观察StaticTest.a和Test.c");
        se.b=5;
        StaticTest.call();//静态方法用类名直接调用
        se.call();
        se.callins();
        System.out.println("b = " + StaticTest.b);//静态属性用类名直接调用
    }
}


assignment: make a method which can print "hello world!".

package com;
class Car{
    static int count = 0;
    Car() {
          count++;//实例方法可以访问静态变量
    }
    static int getCount(){
        return count;
    }
    int inscal()
    {
        return getCount();//实例方法可以调用静态方法。
    }
}

public class Test{
     public static void main(String[] args){
        System.out.println(Car.getCount());//it's ok
        Car c = new Car();
        System.out.println(c.getCount());//实例可以调用静态方法。马克-to-win
        System.out.println(Car.getCount());

        Car c1 = new Car();
        System.out.println(Car.getCount());
        System.out.println(c1.inscal());
}
}

更多请看:https://blog.csdn.net/qq_44639795/article/details/103128670

 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

mark_to_win

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

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

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

打赏作者

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

抵扣说明:

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

余额充值