Instance variables for Java Access Child class objects

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.