What is abstract class and why its needed ?
Abstract class is used when you don’t want to instantiate a class rather provide some common functionality that other classes can extend.
An abstract class can not be instantiated by itself.
An abstract class contain a mix of abstract and non-abstract methods.
Abstract class Example
Below is an example of such as abstract class.. the method printText() is abstract and the implemention is deferred to an overriding class.
package com.javatutorial; public abstract class TestAbstractClass { public abstract void printText(); public void setText() { System.out.println("Nonabstract method in Abstract class"); } }
Here is an example of child class extending the TestAbstractClass and implementing the abstract method printTest().
package com.javatutorial; public class Hello extends TestAbstractClass { public static void main(String[] args) { Hello h =new Hello(); h.setText(); h.printText(); } @Override public void printText() { System.out.println("Abstract method implement in child class"); } }
If you run this class, the output will be:
Nonabstract method in Abstract class
Abstract method implement in child class
Here are some rules about abstract classes :
– An abstract class can have non abstract methods. By putting non-abstract method in an abstract class, the concrete classes inherit the method implementation.
– An abstract class must be subclassed. So, you can not make a class both abstract and final.
– A class can implement one or more interfaces, but it can extend only one abstract class.
© 2015 – 2018, https:. All rights reserved. On republishing this post, you must provide link to original post