Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

instantiating a class using an interface and an implementation

Tags:

java

Trying to get clarifications on when you create a new variable, based on an interface or abstract class, and new it when a specific implementation.

Example:

IBlah blah = new BlahImpl();

How would you read that out?

Is it:

A reference variable blah of type IBlah is instantiated with the class BlahImpl?

And so the reference variable will be bound to IBlah, and hence only have the methods/instance and static variables of IBlah but use BlahImpl classes implementaiton of those properties/vars?

Just trying to get my terminology corrected.

like image 417
mrblah Avatar asked Aug 16 '26 13:08

mrblah


2 Answers

Interfaces and abstract classes can never be instantiated. What you can do as you have in your example is to instantiate a concrete class but assign the resulting object to an interface.

Consider the following class hierarchy:

    IBlah
      ^
      |
AbstractBlah
      ^
      |
   BlahImpl

If IBlah is an interface and AbstractBlah is an abstract class and BlahImpl is a concrete class, the following lines of code are all invalid:

IBlah blah1 = new IBlah();
IBlah blah2 = new AbstractBlah();
AbstractBlah blah3 = new AbstractBlah();

The following lines of code are both valid:

IBlah blah1 = new BlahImpl();
AbstractBlah blah3 = new BlahImpl();

So you can only instantiate concrete a class but the variable you assign that to can be any super-type (a parent class or interface implemented by the class) of the concrete class.

You can refer to and use the concrete class through the interface or abstract class variable. In fact this is actually encouraged as programming to an abstract class (or interface) makes your code more flexible.

It is possible to create a concrete class from an interface or abstract class in in-place. So if we have an interface like this:

interface IBlah {
    void doBlah();
}

That interface could be implemented and instantiated in one fell swoop like so:

IBlah blah = new IBlah() {
    public void doBlah() {
        System.out.println("Doing Blah");
    }
};
like image 80
Tendayi Mawushe Avatar answered Aug 19 '26 02:08

Tendayi Mawushe


"A BlahImpl object is instantiated, and assigned to variable blah as an implementation of interface IBlah." We could also call it a cast, since there is an implicit cast by assigning it like that.

Edit: your first answer sounds reasonable too, the second one does not.

like image 24
BobMcGee Avatar answered Aug 19 '26 02:08

BobMcGee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!