Jump to content


Photo

Reference Variable Declaration


  • Please log in to reply
1 reply to this topic

#1 Saumyaraj

Saumyaraj

    New Member

  • Members
  • Pip
  • 2 posts

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();
    }
}


#2 Vincent acent

Vincent acent

    New Member

  • Members
  • Pip
  • 5 posts

Posted 02 July 2014 - 09:41 PM

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 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users