java 静态和非静态_java静态方法和非静态方法有什么区别

一、概述

请参见下面的代码段:

代码1

public class A {

static int add(int i, int j) {

return(i + j);

}

}

public class B extends A {

public static void main(String args[]) {

short s = 9;

System.out.println(add(s, 6));

}

}

代码2

public class A {

int add(int i, int j) {

return(i + j);

}

}

public class B extends A {

public static void main(String args[]) {

A a = new A();

short s = 9;

System.out.println(a.add(s, 6));

}

}

这些代码段之间有什么区别?两者都15作为答案输出。

二、详解

静态方法属于类本身,而非静态(aka实例)方法属于从该类生成的每个对象。如果您的方法执行的操作不依赖于其类的单个特征,则将其设为静态(这将使程序的占用空间减小)。否则,它应该是非静态的。

例:

class Foo {

int i;

public Foo(int i) {

this.i = i;

}

public static String method1() {

return "An example string that doesn't depend on i (an instance variable)";

}

public int method2() {

return this.i + 1; // Depends on i

}

}

您可以像这样调用静态方法:Foo.method1()。如果您使用method2尝试该操作,它将失败。但这将起作用:Foo bar = new Foo(1); bar.method2();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值