Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8451075
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T11:08:23+00:00 2026-06-10T11:08:23+00:00

Executed Python code: class Test(object): item = 0 def __init__(self): print(self.item) def test(self): print(self.item)

  • 0

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?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T11:08:25+00:00Added an answer on June 10, 2026 at 11:08 am

    Objects in Python are pretty much just like Dictionaries in Python. You can think of each instance of Test and Subclass as a Dictionary that is updated by the __init__ code and assignments in the body of the class you declare. You can picture the code you wrote working something like this:

    class Test(object):         
        item = 0                # self['item'] = 0
    
        def __init__(self):
            print(self.item)    # print(self['item'])
    
        def test(self):
            print(self.item)    # print(self['item'])
    
    class Subclass(Test):       
        item = 1                # self['item'] = 1
    
    s = Subclass()              # Test.__init__({})
    s.test()                    
    

    Python uses duck-typing, so item is just some property of whatever you happen to have an instance of. Notice that you don’t ever actually have to declare item—you just assign a value. This is why you’re able to “override” the value in the sub-class—because you’re actually just overwriting the old value of the same field. So in the example you gave, the item in Subclass isn’t actually overriding the item in Test; rather, they are the same field in a Python object instance.

    In Java fields actually belong to specific classes. Notice how in your code you actually have two declarations of the field int item: one in Test and one in Subclass. When you re-declare the int item in Subclass you are actually shadowing the original field. See Java in a Nutshell: 3.4.5. Shadowing Superclass Fields for more info.

    I’m not sure exactly what you’re trying to do with your example, but this is a more idiomatic Java approach:

    public class Test {
    
        private int item;
    
        public Test() {
            this(0); // Default to 0
        }
    
        public Test(int item) {
            setItem(item);
            test();
        }
    
        public void test() {
            System.out.println(getItem());
        }
    
        public static void main(String[] args) {
            Subclass s = new Subclass();
            s.test();
        }
    
        public void setItem(int item) {
            this.item = item;
        }    
    
        public int getItem() {
            return item;
        }
    
    }
    
    class Subclass extends Test {
    
      public Subclass() {
          super(1); // Default to 1
      }
    
    }
    

    Notice how the value of item is set via a constructor argument rather than by simple assignment. Also notice how item is private and that there is now a getter and setter method to access it. This is more Java-style encapsulation.

    That seems like a lot of code, but a good IDE (such as Eclipse or IntelliJ) will auto-generate a lot of it for you. I still think it’s a lot of boiler-plate though, which is why I prefer Scala—but that’s a whole different discussion.

    Edit:

    My post grew so long that I lost track of why I wanted to introduce getters and setters. The point is that by encapsulating access to the field you’re able to do something more like what you had in Python:

    public class Test {
       // Same as above . . .
    }
    
    class Subclass extends Test {
    
      private int subclassItem = 1;
    
      public int getItem() {
        return subclassItem;
      }
    
      public void setItem(int item) {
        this.subclassItem = item;
      }
    
    }
    

    Now the item field has effectively been overridden since all access to it is done through the getter and setter, and those have been overridden to point at the new field. However, this still results in 0 1 in the output rather than the 1 1 you were expecting.

    This odd behavior stems from the fact that you’re printing from within the constructor—meaning the object hasn’t actually been fully initialized yet. This is especially dangerous if a this reference is passed outside the constructor during construction because it can result in outside code accessing an incomplete object.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

class test: def __init__(self): test_dict = {'1': 'one', '2': 'two'} def test_function(self): print self.test_dict
I am turning some piece of Python code into OO-code. I define a class
When I import a module that has a class, what code is executed when
I need to create a unit-test for some python class. I have a database
Reading: http://www.python.org/download/releases/2.2/descrintro/#metaclasses A class statement is executed and then the name, bases, and attributes
I want to execute python code from C# with following code. static void Main(string[]
I want to execute some Python code, typed at runtime, so I get the
I have an SGE script to execute some python code, submitted to the queue
I have the following Python code: cursor.execute("INSERT INTO table VALUES var1, var2, var3,") where
This is my Python code - cursor.execute(UPDATE tasks SET task_owner=%s,task_remaining_hours=%s, task_impediments=%s,task_notes=%s WHERE task_id=%s, (new_task_owner,new_task_remaining_hours,new_task_impediments,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.