Post a Job  |   Ask a Question?   |   Already registered? login or register
Munendra Kumar
25/01/2016 10:45 AM

Abstract Class instantiation

Hi guys, i am giving a some piece of logic ,can anyone pls elaborate these Apple apple = new Apple() {}; and when you trying create the object ,compiler says "java does not support instantiation of abstract class.why? and i know abstract class is partial.
Spam    4 Comments

25/01/2016 11:32:50
As per your given code there is no compilation error. Because if Apple is an abstract class then u can't do Apple apple=new Apple(); but u are writing Apple apple=new Apple(){}; that means within the {} braces it will create an anonymous inner class which extend from Apple. So u can assign it to Apple object as child class object can be assigned to base class reference. And it may not be due to java version because java support inner classes from 1.1 But one thing, if your Apple class is final then only it will give compile time error.but error message will be different. check once again

25/01/2016 11:52:30
Hi Munendra, As per Java u can't instantiate Abstract class or interface. Reason :- If sun people give permission to instantiate abstract class then think what will be the problem. Fst abstract class is partial and it contain unimplemented method means only method defination if you call it there are no business logic that's why when u call that method without having any logic it will give performance issues. Second, as u know every method call acquire memory inside java stack area. So if you call the abstract method it will unnecessary aquire memory inside jsa. Which also one problem for memory leak. . As per ur code. Apple a=new Apple (){}; Here u r not create object for abstract class. Internally one anonymous class is created Inside that class ur code will be placed. And a which is reference of ur abstract class by which u hold the object of anonymous class Apple a=new Apple$();

25/01/2016 12:11:03
Apple-----is an abstract class Apple a=new Apple(){}; new Apple(){ }---we are creating child class for Apple class(anonymous innerclass)for that class we are creating an object and holds that object by using Parent (Apple)reference.. new Apple(){ //override the abstract methods if we want } sample code: abstract class Apple{ public abstract void sample(); } public class AbstractTest { public static void main(String[] args) { Apple a=new Apple(){ @Override public void sample() { System.out.println(""); } }; } }

25/01/2016 12:37:22
Thank you guys for reply, yes all you are correct and i know it already.these que is asked in the interview so i wanted to tell about that. and the main reason behind the java does not support instantioan for abstract is , abstraction concept of java,whenever you use abstract keyword in your class so your class will be applied abstraction feature of oop's concept. this what i exactly told to the interviewer and he said great

Languages :