Well, it is the simplest OOP concept, i also know that it happens like this, but i am still confused, since i read it the very first time. I like to post this here. May be someone could provide me such a logic that could satisfy me.
PROBLEM:
We know that a super class's object can refer to a sub class object. i.e.
// Class A class A{ private int a; private int b; A(){ a=0; b=0; } A(int a, int b){ this.a=a; this.b=b; } public show(){ System.out.println(a+","+b); } }
// Class B class B extends A{ private int c; B(){ super(); c=0; } B(int a, int b, int c){ super(a,b); this.c=c; } public show(){ System.out.println(c); } public add(){ System.out.println("Test"); } }
// Main class class Test{ public static void main(String args[]){ A a=new A(1,2); B b=new B(3,4,5); a.show(); // 1 2 b.show(); // 5 b.add(); // Hello a = b; // Super class reference to Sub class. a.show(); // 3,4 b.show(); // 5 a.add(); // Error. } }
I am actually confused at this statement where it gives error.
a.add();
I am confused here. Why it is so? I can not understand, as "a" has been referenced to "b" and we all know the concept of referece. So, why "a" can not call add() here? I know, you will say it's not implemented in A, i know, but why?
DISCUSS PLEASE...