For Java, a normal language, subclasses can call non-private variables in the parent class, but in some special cases
The Java language can invoke variables of subclasses through the parent class
In particular, please follow the example below!
Package com.yonyou.test;/** * Test class * @author Little Hao * @ creation date 2015-3-2 */class base{//defines an instance variable named i private int i = 2;public Base () {this.display ();//Note this represents the object that is currently running, that is, the derived object}public void display () {System.out.println (i);}} Inheriting Base Derived Subclass class Derived extends base{//defines an instance variable named i private int i = 22;//constructor, initializes instance variable i to 222public Derived () {i = 222; ②}public void Display () {System.out.println (i);}} public class Test{public static void Main (string[] args) {//Create Derived constructor Create instance new Derived (); ①}}
What is the final result? Yes, it's 0, it's not an accident, you need to understand
Public Base () {this.display ();//Note that this represents the object that is currently running, that is, the derived object}
This refers to the object that is currently running, so who is currently running the object? Yes, that's the derived object,
Based on the timing of initialization of the object when Java was created (http://www.cnblogs.com/xiohao/p/4349833.html), we know that the variable I in derived is not initialized yet, so the final result is: 0
All right, let's get here today 、、、
Instance variables for Java Access Child class objects