Google+

193. Defining objects for Abstract Classes for accessing its abstract methods







Pre-requisites -

  1. Post#189 Objects cant be created for Abstract Classes
  2. Post#190 Accessing members of Abstract Class using its Sub Class object
  3. Post#191 Assigning SubClass reference to SuperClass and accessing members
  4. Post#192 Defining Objects for Abstract Classes

As we cant create objects for Abstract Classes, there is no way that we can access the abstract methods of Abstract Class using its objects. 

But if we really want to access the abstract methods of abstract class using its own object we have to follow the below steps -

1. Just define the object for Abstract Class instead of creating it
2. Create an object for the subclass of the Abstract Class
3. Assign the reference of subclass object to Abstract Class object
4. Access the members of the Abstract Class using its object having subclass reference

Lets implement this on Eclipse IDE -

1. Launch Eclipse IDE, create a Java Project 'Project 26' as shown below -


2. Create an Abstract Class 'ClassOne' as shown below -


3. Create an Abstract Method say one( ) as shown below -


4. Create a Sub Class say 'SubClass' for the above created abstract class 'ClassOne' as shown below -


5. View the error displayed in the above screen as shown below -


According to this error, we have to implement the abstract method of the superclass 'ClassOne' .

6. Implement the Abstract Method of the super class by selecting 'Add unimplemented methods' in the error message as shown below -


7. Observe that unimplemented abstract method of SuperClass 'ClassOne' got implemented in its subclass 'SubClass' as shown below -


8. Now write the code to print 'Inside Implemented abstract method' as shown -


9. Create another Class 'ClassTwo' with main( ) method to access the abstract method of abstract class as shown below -


10. Define an object for 'Abstract Class' ClassOne, as we cant create the objects for abstract classes as shown below -



11. Create an object for the subclass 'SubClass' as shown below -



12. Assign the object reference of SubClass to the defined object variable of ClassOne abstract class as shown below -



13. Now access the abstract method 'one( )' of abstract class 'ClassOne' using its defined object as shown below -


This is how we can access the abstract methods of abstract class using its defined object.

14. Run the Class 'ClassTwo' and observe that the print statement inside the implemented abstract method is displayed in the output as shown below -






Please comment below to feedback or ask questions.

Creating a sub class using Eclipse IDE options  will be explained in the next post.








No comments:

Followers :)

Blog Index