Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an object of an abstract class and interface

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.

like image 249
gautam Avatar asked Dec 01 '10 05:12

gautam


2 Answers

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>.

like image 158
逆さま Avatar answered Sep 28 '22 12:09

逆さま


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();
    }

}
like image 36
Marcin Avatar answered Sep 28 '22 11:09

Marcin