Java 私有最终静态属性与私有最终属性
在Java中,以下两者之间的区别是什么:Java 私有最终静态属性与私有最终属性,java,static,attributes,private,final,Java,Static,Attributes,Private,Final,在Java中,以下两者之间的区别是什么: private final static int NUMBER = 10; 及 两者都是私有和最终,区别在于静态属性 什么更好?为什么?在应用程序的整个生命周期中,一个静态变量一直保留在内存中,并在类加载期间初始化。每次构造新对象时,都会初始化非静态变量。通常最好使用: private static final int NUMBER = 10; 为什么??这减少了每个实例的内存占用。它可能也有利于缓存命中。这很有意义:static应该用于在特定类型(
private final static int NUMBER = 10;
及
两者都是私有
和最终
,区别在于静态
属性
什么更好?为什么?在应用程序的整个生命周期中,一个
静态变量一直保留在内存中,并在类加载期间初始化。每次构造新对象时,都会初始化非静态
变量。通常最好使用:
private static final int NUMBER = 10;
为什么??这减少了每个实例的内存占用。它可能也有利于缓存命中。这很有意义:static
应该用于在特定类型(又称class
)的所有实例(又称对象)之间共享的东西。一般来说,static
意味着“与类型本身关联,而不是与类型的实例关联。”
这意味着您可以引用静态变量,而无需创建该类型的实例,引用该变量的任何代码都引用了完全相同的数据。将其与实例变量进行比较:在这种情况下,类的每个实例都有一个独立版本的变量。例如:
Test x = new Test();
Test y = new Test();
x.instanceVariable = 10;
y.instanceVariable = 20;
System.out.println(x.instanceVariable);
class A
{
final int f;
static final int sf = 5;
A(int num)
{
this.f = num;
}
void show()
{
System.out.printf("About Object: %s\n Final: %d\n Static Final: %d\n\n", this.toString(), this.f, sf);
}
public static void main(String[] args)
{
A ob1 = new A(14);
ob1.show();
A ob2 = new A(21);
ob2.show();
}
}
打印出10:y.instanceVariable
和x.instanceVariable
是分开的,因为x
和y
指的是不同的对象
您可以通过引用来引用静态成员,尽管这样做不好。如果我们这样做了:
Test x = new Test();
Test y = new Test();
x.staticVariable = 10;
y.staticVariable = 20;
System.out.println(x.staticVariable);
然后打印出20个-只有一个变量,而不是每个实例一个。这样写会更清楚:
Test x = new Test();
Test y = new Test();
Test.staticVariable = 10;
Test.staticVariable = 20;
System.out.println(Test.staticVariable);
这使得这种行为更加明显。现代IDE通常会建议将第二个列表更改为第三个
没有理由像下面那样使用内联声明初始化值,因为每个实例都有自己的编号
,但始终使用相同的值(不可变,并使用文本初始化)。这与所有实例只有一个最终静态
变量相同
private final int NUMBER = 10;
因此,如果它不能更改,那么每个实例都有一个副本是没有意义的
但是,如果在构造函数中初始化,则有意义,如下所示:
// No initialization when is declared
private final int number;
public MyClass(int n) {
// The variable can be assigned in the constructor, but then
// not modified later.
number = n;
}
现在,对于MyClass
的每个实例,我们可以有一个不同但不可变的值number
静态表示“与类关联”;如果没有它,变量将与类的每个实例相关联。如果它是静态的,这意味着您在内存中只有一个;如果没有,则为创建的每个实例都有一个实例。静态意味着只要类被加载,变量就会一直保留在内存中;如果没有它,当变量的实例非常小且是静态的时,可以对其进行gc处理。
没有太大区别,因为它们都是常量。对于大多数类数据对象,静态意味着与类本身相关联的内容,无论有多少个对象是用new创建的,都只有一个副本
由于它是一个常量,它实际上可能不存储在类或实例中,但编译器仍然不允许您从静态方法访问实例对象,即使它知道它们将是什么。如果不将反射API设置为静态,那么反射API的存在也可能需要一些无意义的工作。正如Jon所说,静态变量(也称为类变量)是跨类实例存在的变量
我发现了这样一个例子:
程序的输出如下所示:
正如我们在本例中看到的,每个对象都有自己的类变量副本
C:\java>java StaticVariable
No. of instances for sv1 : 1
No. of instances for sv1 : 2
No. of instances for st2 : 2
No. of instances for sv1 : 3
No. of instances for sv2 : 3
No. of instances for sv3 : 3
静态类是所有类实例和类本身上的相同成员。
每个实例(对象)都有一个非静态变量,因此在您的实际情况下如果不将其设置为静态变量,则会浪费内存。如果您将此变量标记为静态变量,则如您所知,您将需要静态方法再次访问这些值,如果您已经考虑过只在静态方法中使用这些变量,那么这将非常有用。如果是这样,那么这将是最好的
但是,您现在可以将变量公开,因为没有人可以像“System.out”那样修改它,这同样取决于您的意图和您想要实现的目标。根据我所做的测试,静态最终变量与最终(非静态)变量不同!最终(非静态)变量可能因对象而异!!!但只有在构造函数中进行初始化时才可以!(如果它不是从构造函数初始化的,那么它只会浪费内存,因为它会为创建的每个无法更改的对象创建最终变量。)
例如:
Test x = new Test();
Test y = new Test();
x.instanceVariable = 10;
y.instanceVariable = 20;
System.out.println(x.instanceVariable);
class A
{
final int f;
static final int sf = 5;
A(int num)
{
this.f = num;
}
void show()
{
System.out.printf("About Object: %s\n Final: %d\n Static Final: %d\n\n", this.toString(), this.f, sf);
}
public static void main(String[] args)
{
A ob1 = new A(14);
ob1.show();
A ob2 = new A(21);
ob2.show();
}
}
屏幕上显示的是:
关于对象:A@addbf1
决赛:14
静态决赛:5
关于对象:A@530daa
决赛:21
静态决赛:5
希腊一年级匿名IT学生让我们说一下,如果该类不会有超过一个实例,那么哪一个会占用更多内存:
专用静态最终int ID=250;
或
私人最终int ID=250
我知道static将引用内存中只有一个副本的类类型,而非static将位于每个实例变量的新内存位置。但是,在内部,如果我们只比较同一类的一个实例(即不会创建多个实例),那么在一个静态最终变量使用的空间方面是否有任何开销?对于最终,初始化时可以在运行时为其分配不同的值。
比如说
class Test{
public final int a;
}
Test t1 = new Test();
t1.a = 10;
Test t2 = new Test();
t2.a = 20; //fixed
因此,每个实例具有不同的字段a值
对于静态最终版,所有实例共享相同的值,并且在首次初始化后无法更改
class TestStatic{
public static final int a = 0;
}
TestStatic t1 = new TestStatic();
t1.a = 10; // ERROR, CAN'T BE ALTERED AFTER THE FIRST
TestStatic t2 = new TestStatic();
t1.a = 20; // ERROR, CAN'T BE ALTERED AFTER THE FIRST INITIALIZATION.
在阅读答案时,我发现没有真正的测试真正切中要害。这是我的2美分:
public class ConstTest
{
private final int value = 10;
private static final int valueStatic = 20;
private final File valueObject = new File("");
private static final File valueObjectStatic = new File("");
public void printAddresses() {
System.out.println("final int address " +
ObjectUtils.identityToString(value));
System.out.println("final static int address " +
ObjectUtils.identityToString(valueStatic));
System.out.println("final file address " +
ObjectUtils.identityToString(valueObject));
System.out.println("final static file address " +
ObjectUtils.identityToString(valueObjectStatic));
}
public static void main(final String args[]) {
final ConstTest firstObj = new ConstTest();
final ConstTest sndObj = new ConstTest();
firstObj.printAdresses();
sndObj.printAdresses();
}
}
第一个对象的结果:
final int address java.lang.Integer@6d9efb05
final static int address java.lang.Integer@60723d7c
final file address java.io.File@6c22c95b
final static file address java.io.File@5fd1acd3
第二轮选举结果
final int address java.lang.Integer@6d9efb05
final static int address java.lang.Integer@60723d7c
final file address java.io.File@3ea981ca
final static file address java.io.File@5fd1acd3
public class JustFinalAttr {
public final int Number;
public JustFinalAttr(int a){
Number=a;
}
}
...System.out.println(new JustFinalAttr(4).Number);
public class LengthDemo {
public static void main(String[] args) {
Rectangle box = new Rectangle();
System.out.println("Sending the value 10.0 "
+ "to the setLength method.");
box.setLength(10.0);
System.out.println("Done.");
}
}
public class ExperimentFinal {
private final int a;
private static final int b = 999;
public ExperimentFinal(int a) {
super();
this.a = a;
}
public int getA() {
return a;
}
public int getB() {
return b;
}
public void print(int a, int b) {
System.out.println("final int: " + a + " \nstatic final int: " + b);
}
public static void main(String[] args) {
ExperimentFinal test = new ExperimentFinal(9);
test.print(test.getA(), test.getB());
} }
final String CENT_1 = new Random().nextInt(2) == 0 ? "HEADS" : "TAILS";
final static String CENT_2 = new Random().nextInt(2) == 0 ? "HEADS" : "TAILS";
package test;
public class Test {
final long OBJECT_ID = new Random().nextLong();
final static long CLASSS_ID = new Random().nextLong();
public static void main(String[] args) {
Test[] test = new Test[5];
for (int i = 0; i < test.length; i++){
test[i] = new Test();
System.out.println("Class id: "+test[i].CLASSS_ID);//<- Always the same value
System.out.println("Object id: "+test[i].OBJECT_ID);//<- Always different
}
}
}
public class TestClass {
private final static double NUMBER = Math.random();
public TestClass () {
System.out.println(NUMBER);
}
}
public class TestClass {
private final double NUMBER = Math.random();
public TestClass () {
System.out.println(NUMBER);
}
}
public final class Foo
{
private final int i;
private static final int j=20;
public Foo(int val){
this.i=val;
}
public static void main(String[] args) {
Foo foo1= new Foo(10);
Foo foo2= new Foo(40);
System.out.println(foo1.i);
System.out.println(foo2.i);
System.out.println(check.j);
}
}
10
40
20
public class City {
// base price that is always same for all objects[For all cities].
private static double iphone_base_price = 10000;
// this is total price = iphone_base_price+iphone_diff;
private double iphone_citi_price;
// extra price added to iphone_base_price. It is constant per city. Every
// city has its own difference defined,
private final double iphone_diff;
private String cityName = "";
// static final will be accessible everywhere within the class but cant be
// changed once initialized.
private static final String countryName = "India";
public City(String cityName, double iphone_diff) {
super();
this.iphone_diff = iphone_diff;
iphone_citi_price = iphone_base_price + iphone_diff;
this.cityName = cityName;
}
/**
* get phone price
*
* @return
*/
private double getPrice() {
return iphone_citi_price;
}
/**
* Get city name
*
* @return
*/
private String getCityName() {
return cityName;
}
public static void main(String[] args) {
// 300 is the
City newyork = new City("Newyork", 300);
System.out.println(newyork.getPrice() + " " + newyork.getCityName());
City california = new City("California", 800);
System.out.println(california.getPrice() + " " + california.getCityName());
// We cant write below statement as a final variable can not be
// reassigned
// california.iphone_diff=1000; //************************
// base price is defined for a class and not per instances.
// For any number of object creation, static variable's value would be the same
// for all instances until and unless changed.
// Also it is accessible anywhere inside a class.
iphone_base_price = 9000;
City delhi = new City("delhi", 400);
System.out.println(delhi.getPrice() + " " + delhi.getCityName());
City moscow = new City("delhi", 500);
System.out.println(moscow.getPrice() + " " + moscow.getCityName());
// Here countryName is accessible as it is static but we can not change it as it is final as well.
//Something are meant to be accessible with no permission to modify it.
//Try un-commenting below statements
System.out.println(countryName);
// countryName="INDIA";
// System.out.println(countryName);
}
}