0

If A abc = new B() and A , B classes are having inheritance relationship, what is the advantage of using reference type A instead of B, what if B was used? Also what methods can now B's object access(all A and B methods or something else)? Also if A and B both have same methods, B overrides it, but if they've different methods, object can access whose methods here?

2 Answers2

1

Suppose you have:

public class A {

    public void a(){

    }
}

public class B extends A{

    public void b(){

    }
}

You can NOT use B b = new A();

You can use A a = new A(); Here you have access to a() method.

You can use A a = new B(); Here you have access to a() method.

You can use B b = new B(); Here you have access to both a(), b() methods.

So what is the advantage of having A a = new B()?

Suppose you have classes B, C, D, E and all of them extend the class A or implement the interface A. Now you can have A a = new B(); A a = new C(); A a = new D() and check the type at runtime then cast the object to specific class type so you do NOT need to declare 3 variable for each type. You have one container(variable) for all A type variable and it's child (B, C, D) too.

Ehsan Mashhadi
  • 2,568
  • 1
  • 19
  • 30
0

Let's take Java Collections API as an example. For sake of brevity, consider the following hierarchy:

Collection -> ArrayList

Now, these statements are valid:

  • An instance of Collection can use the method isEmpty().
  • An instance of ArrayListcan use methods isEmpty() and add().

Now it depends what do you want to do with the instance. If you need to add new elements, use the implementation which allows it. If not, it's a good practice to use the minimal implementation or object you really need.

Example: If you need a size of the returned List from DAO, use the Collection instead of List or any of its implementations:

Collection collection = dao.getListFromDatabase();
int size = collection.size();
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183