Shoaib Ansari
Shoaib Ansari

Reputation: 21

Create an Instance of an abstract class

package corejava;
abstract class abstractA      // abstract class A
{
    abstract void abst();         // Abstarct Method
    void eat()                    // Non abstract method
    {
        System.out.println("non abstract");
    }
}
class B extends abstractA        // class B extends abstract Class
{
    @Override                          // define body of abstract method
    void abst() {
        System.out.println("abstract method define");
    }
    void eat()                         // override eat method
    {
        System.out.println("non abstract override ");
    }
}
public class alloops {             // Main class
    public static void main(String[] args)
    {
        B b=new B();                         // create Object B Class
        abstractA a = new abstractA() {          // create Object of abstract Class
            @Override
            void abst() {
                System.out.println("again abstract");
            }
        };
        a.eat();  //instance of abstract class
        System.out.println(a instanceof abstractA);
        b.abst();
        b.eat();
        a.abst();
    }
}

Output:
non abstract
true,
abstract method define
non abstract override
again abstract

In this case output is above. I want to know if it's right or wrong. Do I have have to create an instance of the abstract class or not?

Upvotes: 2

Views: 1792

Answers (3)

mirmdasif
mirmdasif

Reputation: 6354

You can't create an instance of abstract class.You are creating an instance of anonymous inner class which is extending your abstract class. Confusion is creating because this line is returning true.

   a instanceof abstractA

instanceof is used to check if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.

In this case abstractA is an instace of abstract class's subclass.

Output will be more clear if you use these lines to determine class types of instances

  System.out.println(b.getClass().toString());
  System.out.println(a.getClass().toString());

Output:
class corejava.B
class corejava.alloops$1

First line of the output tells that b is an instance of class B in package corejava

Second line tells that a is the first anonymous inner class ($1) of class alloops of package corejava

Upvotes: 0

user238680
user238680

Reputation: 3

abstractA a = new abstractA() { 
     @Override
      void abst() {
                System.out.println("again abstract");
      }
};

The above code actually defined an anonymous class extending your abstract class. Your code works as it's expected.

Upvotes: 0

What you have done is creating an anonymous inner class.

abstractA a = new abstractA() {          // create Object of abstract Class
        @Override
        void abst() {
            System.out.println("again abstract");
        }
    };

Upvotes: 2

Related Questions