-2

Why would you declare the "thing" object as the super-class when you can use the subclass, which would give you access to all of the same methods and fields and wouldn't require type casting for methods in the B class.

public class A{}
public class B extends A{}

public class main()
{
  A thing = new B();
}
  • 2
    [What does it mean to “program to an interface”?](https://stackoverflow.com/q/383947) – Pshemo Apr 12 '19 at 11:52

3 Answers3

3

This is called Polymorphism. If you had another class called C extends A you could create a List<A> and put both B and C there. Then you could iterate over them and call the common method etc.

Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107
2

Maybe because you want to feed() several Animals at same time, without caring about the real type of Animal:

interface Animal { void feed();}
class Dog implements Animal { public void feed() { /* feed a dog (give it a cat) */ }}
class Cat implements Animal { public void feed() { /* feed a cat (give it a bird) */ }}
class Cow implements Animal { public void feed() { /* feed a cow (give it some grass) */ }}

// Now I have some animals mixed somewhere (note that I am allowed to have the array declaring a supertype (Animal), and it can contain many kind of different animals)
Animal[] manyAnimals = new Animal[]{ new Dog(), new Cat(), new Cow() };

// I can feed them all without knowing really what kind of Animal they are. I just know they are all Animal, and they will all provide a feed() method.
for(Animal some : manyAnimals) { some.feed(); }

It is polymorphism.

spi
  • 1,673
  • 13
  • 19
0

This example might help you understand it.

In a company there are both Permanent and Contract employees are there. The salary calculations happen differently for different type of employee. But PF calculation is common for both type of employees. So in this case you can write common code in super class(Employee) and only custom code in sub class(PermanentEmployee and ContractEmployee). This way you can make code reusable instead of writing again and again and also you can achieve dynamic polymorphism. Most of the time the type of employee is decided at run time.

Pradyskumar
  • 296
  • 1
  • 3
  • 15