# Inheritance and Polymorphism Questions

Page 1 of 1

## 1 Replies - 533 Views - Last Post: 10 July 2012 - 06:05 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=285422&amp;s=ca8f48a6eb2608f8cdbfbcc523d6c779&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 Jumangi85

Reputation: 0
• 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

• Monomania

Reputation: 513
• Posts: 2,063
• 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?