-3
public class SuperClass {}
public class ChildClass extends SuperClass {}

SuperClass  A = new ChildClass();

ChildClass B  = new ChildClass(); 

With both the instances A & B, we can only access the protected methods of super class . Then what is the difference between the two and which places they come into use ? Thanks in advance

T.Gounelle
  • 5,953
  • 1
  • 22
  • 32
Muthu Raman
  • 154
  • 2
  • 13
  • 1
    No, with `B` you can access all the public methods of `ChlidClass` as well. I would leave `protected` out of it at the moment, as that's a more complex set of rules... – Jon Skeet Mar 30 '15 at 10:15
  • This is Dynamic binding/Runtime binding/Method overriding. http://stackoverflow.com/questions/20783266/what-is-the-difference-between-dynamic-and-static-polymorphism-in-java – Pratik Mar 30 '15 at 10:21

2 Answers2

0
a.getClass().getName();

Why does this matter?

public class SuperClass {}
public class SonClass extends SuperClass {}
public class DaughterClass extends SuperClass {}

SuperClass[] Arr = new SuperClass[2];
Arr[0] = new SonClass();
Arr[1] = new DaughterClass()
Maarten
  • 7
  • 1
0

It's matter of what additional public methods B will provide compared to A and how the client code will use the instance created.

If you take the List and ArrayList (List is an interface but it's valid for the example), very often you will choose the class implementation for its own capabilities: ArrayList is an auto-increasing vector that provide constant access to its elements. But the client of the class may not really care about the kind of List implementation, and you will have more flexibility to just use this instance as a simple List that provide the list abstraction.

Another case is about polymorphism. If you extends your example with an other class, e.g.

 public class AnotherChildClass extends SuperClass {}

And you need to process a list of objects from the 2 child classes, e.g.

List<SuperClass> myList = new ArrayList<>();
myList.add(new ChildClass());
myList.add(new AnotherChildClass());
myList.add(new ChildClass());
//...

// later
(for (SuperClass s : myList) {
   s.doSomeThing();
}

provided the method doSomeThing() has been declared in SuperClass and implemented by both children classes (or implemented in SuperClass and possibly overridden).

Your question relates to a fundamental part of OOP which is abstraction.

T.Gounelle
  • 5,953
  • 1
  • 22
  • 32