Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this an Instantiation of Abstract Class?

Tags:

java

If Abstract class cannot be instantiated, then how can the variables access and methods access of the abstract class A even without extending is achieved in the class check (as you can see in the below code)

Is the created a an object of abstract class A?

CODE

    abstract class A
    {
        int a=10;
        public A()
        {
            System.out.println("CONSTRUCTOR ONE");
        }
        public A(String value)
        {
            System.out.println("CONSTRUCTOR "+value);
        }
        void add(int sum)
        {
            System.out.println("THE SUM IS:"+sum);
        }
        int sub(int a,int b )
        {
          return(a-b);
        }
    }

    public class check
    {
        public check()
        {
            new A("TWO"){};
        }
        public static void main(String args[]) 
        {
             int a,b,sum;
             a=10;
             b=15;
             sum=a+b;
             A s = new A() {};
             new check();
             s.add(sum);
             int subb=s.sub(35,55);
             System.out.println("THE SUB IS:"+subb);  
             System.out.println("THE VALUE OF A IS:"+s.a);
        }
    }

OUTPUT

CONSTRUCTOR ONE
CONSTRUCTOR TWO
THE SUM IS:25
THE SUB IS:-20
THE VALUE OF A IS:10
BUILD SUCCESSFUL (total time: 0 seconds)
like image 453
user1046833 Avatar asked Dec 10 '22 04:12

user1046833


1 Answers

The new A() {} call creates an anonymous subclass and instantiates that. Since A does not contain any abstract methods, this works.

like image 158
ibid Avatar answered Dec 20 '22 09:12

ibid