You are here:

Java/inheritance problem with references

Advertisement


Question
Dear Sir,
i m confused with very simple example of Inheritance like.
class A
{
  int k=1;
  void show()
  {
    System.out.println("===inside A class= Show()=="+k);
   }
}
class B extends A
{
  int k=8;
  void show()
  {
     
     System.out.println("===inside B class=Show()=="+k);
  }
  void show1()
  {
     
     System.out.println("===inside B class show1() ===");
  }
}

public class Inheritance
{
 public static void main(String s[])
 {
     A a=new B();
     a.show();
     //a.show1();//error
     System.out.println("===="+a.k);
        
 }
}
in the above example i m making reference of superclass  to Subclass object. No i have two Question.
1-Why we Do means===> A a=new B(); Why not use B=new B(); or A a=New A();When We should do Like it A a=new B();
2-when i call a.show(); its print "==inside B class=Show()==" while it should show "==inside A class= Show()==" because as i know Reference Of A class know only A class member only.
because if i will  a.show1(); it give Error Because show1() is function of class B. and if i print a.k it show "1". why not "8" defined in Class B.

Answer
Hello,

In the statement A a= new B();
the a object has both the A.a variable and also the B.a variable because the B class is a subclass of the A class. Now, since they both have the same signature methods, the show() method in the parent class(Class A) is "hidden" and the compiler takes the "discovered " method which is the one in class B. Now, when you print it out in the statement System.out.println("===="+a.k), you are referring to the a value at compile time. so, it goes to fetch the variable in the A class. Remember that it has a type "A " . You can make statements like this :

A a  =new A(); and B b= new B(); You are correct why you can't call a.show1() because method show1() does not exist in class A and at runtime, the compiler goes to class A and won't find that method..  

Java

All Answers


Answers by Expert:


Ask Experts

Volunteer


henry joe

Expertise

I can confidently answer questions relating to JSE and JEE6 . Please no questions on JME.

Experience

I am experienced in JSE and JEE6

Education/Credentials
I am a BSEng graduate

©2016 About.com. All rights reserved.