A Java pen question from Shanghai Group Shuo software company

Source: Internet
Author: User

The requirement is to write the results and explain why. The recalled program is like this: [java package org; public class Test {public static void main (String [] args) {A a = new B ();. print () ;}} class A {private int I = 1; public A () {int I = 2;} public void print () {System. out. println ("The result is:" + I) ;}} class B extends A {private int I = 3; public B () {int I = 6 ;} public void print () {System. out. println ("The result is:" + I) ;}} The output result is: 3. This question examines polymorphism. here is the reference of the parent class The object pointing to the subclass. the reference of the parent class can only access methods that are common to the Child class and the parent class. the execution sequence of this program is as follows through Eclipse and Debug: [java] package org; public class Test {public static void main (String [] args) {A a = new B ();. print () ;}} class A {// 3 private int I = 1; // 2 public A () {// 4 int I = 2;} public void print () {System. out. println ("The result is:" + I) ;}} class B extends A {// 5 private int I = 3; // 1 public B () {// 6 int I = 6;} public void pr Int () {System. out. println ("The result is:" + I) ;}} change The program slightly: [java] package org; public class Test {public static void main (String [] args) {A a = new B ();. print () ;}} class A {// 3 private int I = 1; // 2 public A () {// 4 int I = 2;} public void print () {System. out. println ("The result is:" + I) ;}} class B extends A {// 5 private int I = 3; // 1 public B () {// 6 int I = 6;} public void Print2 () {System. out. println ("The result is:" + I) ;}then The output result is 1. because the reference of the parent class cannot access the method unique to the subclass.

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.