Java/Inheritance

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
1. A is assignment compatible with B. In cases where code already uses a reference to A, you can have an instance of B there instead E.g., we can freely mix A and B instances in a A reference:
A[] array = new A[4];
array[0] = new A();
array[1] = new B();
array[2] = new A();
array[3] = new B();
for(int i = 0; i < array.length; i++) {
  array[i].show();
}

2. When B extends A, it has the same method, show(), as A, in which case B's show() gets called instead of A.

Fields unlike methods don't override if they have the same name, they only shadow. If you "a.k" it will go and look at class A for what k is since a is declared as an A. If you cast a reference of A to B, then ask what the field k is you will get 8. Note that casting only works if the value stored in A was actually created as a B.

Java

All Answers


Answers by Expert:


Ask Experts

Volunteer


Artemus Harper

Expertise

I have a Masters in computer science. I can answer questions on core J2SE, swing and graphics. Please no questions about JSP or J2ME.

Experience

I have experience in Core Java, good background in Java swing/gui, some experience with JNI, Java reflection. Some experience in bio-informatics. Basics in c++ and c#

Organizations
Washington State University

Education/Credentials
MS in Computer Science from Washington State University and a BS in Mathematics and Computer Science from Central Washington University.

©2016 About.com. All rights reserved.