O'Reilly Forums: Reference Variable Declaration - O'Reilly Forums

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Reference Variable Declaration

#1 User is offline   Saumyaraj 

  • New Member
  • Pip
  • Group: Members
  • Posts: 2
  • Joined: 20-September 12

Posted 20 September 2012 - 05:26 AM

I am aware of the essence of polymorphism i.e I can declare a reference variable of type superclass and assign it to a subclass object but why i am not able to declare a reference variable of type subclass and refer it to superclass object....plzzz help
package confusion;
class Sup
{    
    void print()
    {
    System.out.println("hello");
    }
}
public class Sub extends Sup
{
    public static void main(String[] args)
    {
  Sub ob= new Sup();
  ob.print();
    }
}

0

#2 User is offline   Vincent acent 

  • New Member
  • Pip
  • Group: Members
  • Posts: 4
  • Joined: 18-May 14

Posted 02 July 2014 - 09:41 PM

View PostSaumyaraj, on 20 September 2012 - 05:26 AM, said:

I am aware of the essence of polymorphism i.e I can declare a reference variable of type superclass and assign it to a subclass object but why i am not able to declare a reference variable of type subclass and refer it to superclass object....plzzz help
package confusion;
class Sup
{    
    void print()
    {
    System.out.println("hello");
    }
}
public class Sub extends Sup
{
    public static void main(String[] args)
    {
  Sub ob= new Sup();
  ob.print();
    }
}


Because it doesn't make sense to assign the Object of the superclass to the reference type of its subclass. We could say "Wolf IS AN Animal", but it doesn't make sense to say "Animal IS A Wolf" because not all Animal is Wolf. Plus, we all know that the subclass can have an additional method which the superclass doesn't have thus not all Animal can roar() just like the Wolf do. I hope you get the picture i trying to say here. In Java, you're only allowed to call a method that the reference type has regardless of the object you assigned to that reference variable.
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users