How to create an object of an abstract class and interface
Solution 1
You can not instantiate an abstract class or an interface - you can instantiate one of their subclasses/implementers.
Examples of such a thing are typical in the use of Java Collections.
List<String> stringList = new ArrayList<String>();
You are using the interface type List<T>
as the type, but the instance itself is an ArrayList<T>
.
Solution 2
To create object of an abstract class just use new just like creating objects of other non abstract classes with just one small difference, as follows:
package com.my.test;
public abstract class MyAbstractClass {
private String name;
public MyAbstractClass(String name)
{
this.name = name;
}
public String getName(){
return this.name;
}
}
package com.my.test;
public class MyTestClass {
public static void main(String [] args)
{
MyAbstractClass ABC = new MyAbstractClass("name") {
};
System.out.println(ABC.getName());
}
}
In the same way You can create an object of interface type, just as follows:
package com.my.test;
public interface MyInterface {
void doSome();
public abstract void go();
}
package com.my.test;
public class MyTestClass {
public static void main(String [] args)
{
MyInterface myInterface = new MyInterface() {
@Override
public void go() {
System.out.println("Go ...");
}
@Override
public void doSome() {
System.out.println("Do ...");
}
};
myInterface.doSome();
myInterface.go();
}
}
Solution 3
There are two ways you can achieve this.
1) Either you extend / implement the Abstract class / interface in a new class, create the object of this new class and then use this object as per your need.
2) The Compiler allows you to create anonymous objects of the interfaces in your code.
For eg. ( new Runnable() { ... } );
Hope this helps.
Regards, Mahendra Liya.
Solution 4
You can provide an implementation as an anonymous class:
new SomeInterface() {
public void foo(){
// an implementation of an interface method
}
};
Likewise, an anonymous class can extend a parent class instead of implementing an interface (but it can't do both).
Solution 5
public abstract class Foo { public abstract void foo(); }
public interface Bar { public void bar(); }
public class Winner extends Foo implements Bar {
@Override public void foo() { }
@Override public void bar() { }
}
new Winner(); // OK
Related videos on Youtube
gautam
Updated on July 09, 2022Comments
-
gautam almost 2 years
How do I create an object of an abstract class and interface? I know we can't instantiate an object of an abstract class directly.
-
user609239 almost 13 yearsfoo() method in abstract class requires keyword abstract, otherwise it throws compile time error. It should be like, public abstract void foo();
-
Deltharis over 9 yearsThat is NOT an object of abstract class or interface. That is an anonymous class extending(implementing) said abstract class(interface). Huge conceptual difference.