[英]Sorting out few questions I am unsure about with Java
package Day4;
public class clasAndobjDemo {
static int a = 90; //Data memeber ,Properties
static int b = 100; // Data Memeber Poperties
public static void main(String[] args) {
clasAndobjDemo obj1 = new clasAndobjDemo();
obj1.sub();
obj1.sum();
System.out.println(obj1.a);
System.out.println(obj1.b);
System.out.println(a);
System.out.println(b);
}
public void sub() {
int x = 80, y = 100, z = x - y;
System.out.println("Print" + z);
}
public void sum() {
int x = 80, y = 100, z = x + y;
System.out.println("Print" + z);
}
}
Output for above code is:上面代码的输出是:
Print 20
打印 20
Print 80打印 80
9090
100100
9090
100100
Can someone please help me to understand why I am getting:有人可以帮我理解为什么我得到:
90
90
100100
9090
100.100。
A static variable can be accessed in many ways.可以通过多种方式访问静态变量。
Static variables can be accessed directly in both static/non-static method.静态变量可以在静态/非静态方法中直接访问。 Also, a static variable can be accessed from an object.
此外,可以从对象访问静态变量。
System.out.println(obj1.a);
However, the above method is discouraged.但是,不鼓励使用上述方法。
Since static variables are owned by the class(only one copy for all the objects), you can access them without using instance references.由于静态变量归类所有(所有对象只有一份副本),因此您可以在不使用实例引用的情况下访问它们。
ie directly(within the class itself)即直接(在类本身内)
System.out.println(a);
or using classname或使用类名
clasAndobjDemo.a
References : https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html参考资料: https : //docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.