Google+

127. Objects can't be created for abstract Classes







Object cant be created for abstract class to directly access the members of the abstract class. In order to access the members of the abstract class, we've to create a subclass for abstract class and implement the abstract methods of abstract class. We can then access the inherited abstract and non-abstract methods of abstract class by creating an object for subclass.

Lets implement this on Eclipse IDE:

1.Create abstract class 'Superclass' containing abstract and non-abstract methods as shown below:



2. Create a class 'AbstractClassObjectDemo' to create an object for accessing the abstract class 'Superclass' as shown below:



3. Observe that the error "Cannot initiate the Superclass type" is displayed as shown below:



After looking at this error, its very clear that we cannot create objects for the classes of 'abstract' type

So, In order to access to access the abstract and non-abstract methods of abstract class, we've to create a subclass for abstract class and create an object for subclass to access the inherited abstract and non-abstract methods of abstract class as shown below:

4. Create subclass 'Subclass' for 'Superclass' as shown below:



5. Create  class 'SubclassObject' to create an object for Subclass to access the abstract and non-abstract methods inherited by the Subclass from Superclass as shown below:




6. Save and Run the 'SubclassObject' class
7. Observe that the output is displayed in the console as shown below:



Download this project:

Click here to download the project containing the class files used in this post (You can download the project and import into Eclipse IDE on your machine)



Please comment below to feedback or ask questions.

'Abstract classes can partially implement the Interfaces' will be explained in the next post.




No comments: