Difference between inheritance in Java and Python

Viewed 1452

Executed Python code:

class Test(object):
    item = 0

    def __init__(self):
        print(self.item)

    def test(self):
        print(self.item)

class Subclass(Test):
    item = 1


s = Subclass()
s.test()

gives:

1
1

Executed analogical Java code:

public class Test {
    int item = 0;

    Test(){
        System.out.println(this.item);
    }

    void test(){
        System.out.println(this.item);
    }

    public static void main(String[] args){
        Subclass s = new Subclass();
        s.test();
    }
}

class Subclass extends Test {
    int item = 1;
}

gives:

0
0

Apparently, Java method inherited from base class (Test) uses also base class' member variables. Python method uses the member variable of derived class (Subclass).

The question: Is there any way to achieve the same or at least similar behaviour in Java like in Python?

3 Answers
Related