0

I just started learning Java and I am confused about creating a new object when I have a child class extends its parent class and/or also implements a interface.

For example, if I have:

Parent class: Animal class with methods walk, eat, sleep Child class: Bird class with a method sing Interface: Flyable with a method fly

And "Bird extends Animal implements Flyable" or just "Bird extends Animal"

So when I create new objects, I can have:

  1. Animal bird1 = new Animal();
  2. Animal bird2 = new Bird();
  3. Bird bird3 = new Bird();
  4. Flyable bird4 = new Bird();

As I understand it (if I didn't misunderstand anything...), unless I cast the object when calling the methods, for 1. and 2. I can call all the methods in Animal; for 3. I can call every method in Animal, Bird, and/or Flyable(if I implemented it); for 4. I can only call the method in Flyable.

So my question is, why not we only create 3. in Java because we can use all the methods in parent class and child class, why and when do we need 1. 2. and 4.?

Thanks for the help!

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • 1
    In general, you probably wouldn't use those. The point of base classes and interfaces is more for what *accepts* those types. (1) here doesn't make much sense unless you explicitly want an `Animal`, your naming here is confusing if it's not actually a `Bird`. – Dave Newton Jul 26 '18 at 19:50
  • 1
    (4) You would use if you wanted to interact with an object that can fly, but didn't care whether it was an `Animal` or not. Suppose you wanted an `ArrayList`. You could put `Bird` objects, `Helicopter` objects, `Kite` objects and whatever else in it. But if you wanted `ArrayList` and didn't care whether it could fly, then you could use the other ones. – mypetlion Jul 26 '18 at 19:54

0 Answers0