0

I'm now learning java inheritance and I have a problem: if there're two classes:

public class A{
   //code of class A
}
public class B extends A{
   //code of class B
   //code in B rewrite some methods in A
}

and, if I want to use those classes and create a 'B' object in my client program. Are there any difference between

A objectName = new B();

and

B objectName = new B();

?

Thanks.

Trevor
  • 1
  • 1
    `A objectName = new B();` will only allow you to access the properties and methods defined by `A` - this is part of polymorphism – MadProgrammer Dec 12 '17 at 00:50
  • The first would also allow easy swapping in of an alternative subclass, e.g. `C extends A` e.g. for performance or implementation reasons, whilst making sure you code still works – SteveR Dec 12 '17 at 00:56

2 Answers2

0

Take a look at this link, it might be helpful: Polymorphism: Why use "List list = new ArrayList" instead of "ArrayList list = new ArrayList"?

To help out in my own words, basically, when you use the inherited object, it makes it easier to deal with conversions between all children of the parent object, as well as allow you to use specific methods for each object.

Cheers!

Jacob B.
  • 423
  • 3
  • 12
0

This is polymorphism. With the first one:

A objectName = new B();

You can change the object reffered by objectName without worrying about the changing the base type like this:

objectName = new ChildOfA();

By instantiating an object through parent type you can store every child object in a container as long as it is created through parent type('A')

Ex:

List container = new ArrayList<A>();
container.add(new B());
container.add(new ChildOfA());

But this one is not allowed, as a result it lacks flexibility.

container = new ArrayList<B>();
container.add(new ChildOfA()); //error because childOfA is not of type of B
Lorence Hernandez
  • 1,189
  • 12
  • 23