1
class A {
.
.
.
}

class B extends A {
.
.
.
}

A var = new B() works. But when would I need to do this rather than a simple B var = B()? What difference does it make? Anything different while using var.method() or var.field?

Prasad Kharkar
  • 13,410
  • 5
  • 37
  • 56
user1265125
  • 2,608
  • 8
  • 42
  • 65

5 Answers5

1

if you do A var = new B(); you can also assign var = new C() if C extends A. This is polymorphism principal. You can assign instances of multiple classes which pass IS-A test for class A.

Prasad Kharkar
  • 13,410
  • 5
  • 37
  • 56
0

But when would I need to do this rather than a simple B var = B()? > What difference does it make?

I often use an abstract type when declaring a variable, but assign an instance of a concrete type to it:

List<Integer> list = new ArrayList<Integer>();

This makes it easier to substitute a different concrete list implementation at a later point.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

You would use the most super class or ideally interface which is appropriate. This demonstrates in code the minimal functionality you need and if you need to change the code from

 A var = new B();

to

 A var = new C(); // C also extends A

This is trivial. However if you use B everywhere, you are making mroe work for yourself later to change and check the code.

The only exception is when you can make the object too generic and miss some important behaviour. e.g.

 void methodIsInSet(Set<T> set);

could be replaced with

 void methodIsInSet(Collection<T> set);

as the methods are the same, but leaves out what might be important assumptions about duplicates etc.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

You normally don't do that in a simple statement such as A var = new B(), so your observation is in many cases correct. However, you'll use it whith something like

public A CreateAnObject(int i)
{
    if (i = 0)
        return new A();
    else 
        return new B();
}

Now you can do a A var = CreateAnObject(something). And var will be either A or B.

PMF
  • 14,535
  • 3
  • 23
  • 49
  • 1
    I always do that when using Collections classes. Like `List myList = new ArrayList();` – Matthias Oct 28 '13 at 07:54
  • Ok, that is a good point. So it's basically "if you know that you will only need the interface of A, declare the var as A". Actually a good tip. – PMF Oct 28 '13 at 08:34
0

Case 1. JDBC is an example. You use Connection, Statemet interface to refer objects, but the provider implements for you class say ConnectionImpl and StatementImpl (here we never bother about names.).

Case 2: Interface is generic representation and implementation is specific representation. when you use interface, same reference can be useful to other implementation class objects.

Chowdappa
  • 1,580
  • 1
  • 15
  • 31