Abstract class having constructor, data member, methods etc
Abstract class having constructor, data member,
methods etc.
An abstract class can have
data member, abstract method, method body, constructor and even main() method.
- //example of abstract class that have method body
- abstract class Bike{
- Bike(){System.out.println("bike is created");}
- abstract void run();
- void changeGear(){System.out.println("gear changed");}
- }
-
- class Honda extends Bike{
- void run(){System.out.println("running safely..");}
- }
- class TestAbstraction2{
- public static void main(String args[]){
- Bike obj = new Honda();
- obj.run();
- obj.changeGear();
- }
- }
bike is created
running
safely..
gear changed
Rule: If there is any abstract method in a class, that
class must be abstract.
- class Bike12{
- abstract void run();
- }
Compile time error
Rule: If you are extending any abstract class that have abstract method, you must either
provide the implementation of the method or make this class abstract.
Another real scenario of abstract class
The abstract class can
also be used to provide some implementation of the interface. In such case, the
end user may not be forced to override all the methods of the interface.
Comments
Post a Comment