Google+

126. Abstract methods in Superclass must be implemented in Subclass






If we have abstract methods in a class, then we've to create subclass for the class and override the abstract methods by implementing them in subclass. Java will give an error if we don't implement the abstract methods of superclass in subclass.

Lets implement this on Eclipse IDE (First lets find out what happens when we don't implement the abstract methods of Superclass in Subclass)

1. Create a class 'Superclass' containing abstract method as shown below:



2. Observe that error 'The abstract method add( ) can only be defined by abstract class' is displayed as shown below:



3. Lets specify the 'Superclass' as 'abstract' type to resolve the above error and observe that the above error got resolved as shown  below:



4. Lets add one more non-abstract method in 'Superclass' abstract class as shown below:























5. Create subclass 'Subclass' for 'Superclass' as shown below and don't implement the abstract methods of 'Superclass' in 'Subclass' as shown below:





6. Observe that error 'The subclass must implement the inherited abstract method add( ) of superclass' is displayed as shown below:



7. Implement the abstract method 'add( )' of 'Superclass' in 'Subclass' as shown below:



8. Create class 'AccessAbstractMethod' to create an object for 'Subclass' for accessing the inherited abstract and non-abstract methods of Superclass as shown below:



9. Save and Run the 'AccessAbstractMethod' class
10. 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.

'Objects can't be created for abstract classes' will be explained in the next post.



No comments:

Blog Index