Skip to content Skip to sidebar Skip to footer

Static Attributes (python Vs Java)

What is the difference between Python class attributes and Java static attributes? For example, in Python class Example: attribute = 3 in Java public class Example { priv

Solution 1:

In Python, you can have a class variable and an instance variable of the same name [Static class variables in Python]:

>>>classMyClass:...    i = 3...>>>MyClass.i
3 

>>>m = MyClass()>>>m.i = 4>>>MyClass.i, m.i>>>(3, 4)

In Java, you cannot have a static and non-static field with the same name (the following will not compile, you get the error "Duplicate field MyClass.i"):

publicclassMyClass {
  privatestaticint i;
  privateint i;
}

additionally, if you try to assign a static field from an instance, it will change the static field:

publicclassMyClass {
  privatestaticint i = 3;

  publicstaticvoidmain(String[] args) {
    MyClass m = new MyClass();
    m.i = 4;

    System.out.println(MyClass.i + ", " + m.i);
  }
}

4, 4


In both Java and Python you can access a static variable from an instance, but you don't need to:

Python:

>>>m = MyClass()>>>m.i
3
>>>MyClass.i
3

Java:

publicstaticvoidmain(String[] args) {
    System.out.println(new MyClass().i);
    System.out.println(MyClass.i);
  }

3 3

Post a Comment for "Static Attributes (python Vs Java)"