1 Replies - 443 Views - Last Post: 10 July 2012 - 06:05 PM Rate Topic: -----

#1 Jumangi85  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 24-June 12

Inheritance and Polymorphism Questions

Posted 10 July 2012 - 05:49 PM

Hello -

I am learning about polymorphism and inheritance! I'm working through some practice problems and I'd like to see if my thinking is correct.

public class Child extends Base
{
  public void saySomething() 
  {
      System.out.println("I am type Child");
  } 
}  



public class Base
{    
   public void saySomething() 
   {
      System.out.println("I am type Base");
   }
   
   public void saySomething(String x) 
   {
      System.out.println("Base says " + x);
   }
   
   public static void main(String[] args)
   {
      // Problem One
      Child c = new Child();
      c.saySomething("Hello");
			
      // Problem Two			
      Base b = new Child();
      b.saySomething();	
			
      // Problem Three			
      Base d = (Base) new Child();  
      d.saySomething();	
			
      //  Problem Four		
      Base base = new Base(); 
      Child child;			
      child = (Child) base;	
   }
}



Problem One:
No casting involved.
Java looks at the Child class for a saySomething(String x) method.
It doesn't find one, so it then moves up the hierarchy and looks at the parent class - Base.
It find a saySomething(String x) method in Base and calls it.
"Base says Hello"

Problem Two:
Casting up the hierarchy.
Normally in this case, I would say that Java can only call the methods found in class Base.
But, with runtime binding, I'm thinking Java would call the Child class saySomething method? - Is that right?
"I am type Child"

Problem Three:
Casting up?
"I am type Base"

Problem Four:
Exception - you can't cast a base object down to a child object?

Is This A Good Question/Topic? 0
  • +

Replies To: Inheritance and Polymorphism Questions

#2 fromTheSprawl  Icon User is offline

  • Monomania
  • member icon

Reputation: 513
  • View blog
  • Posts: 2,056
  • Joined: 28-December 10

Re: Inheritance and Polymorphism Questions

Posted 10 July 2012 - 06:05 PM

Congratulations. You've aced the exam.

Now try working with Abstract classes and Interfaces?
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1