Lets take an example of a Car, every car has seats but the number of seats vary based on the type of car. A sports car will have 2 seats and an economic family car has 4 seats. At this point the common feature for every car are seats, so we need to create an Abstract class called Car and an abstract method called seat. Than we can create 2 sub-classes called SportsCar and EconomicCar that will override the seat method of Car class.
public abstract Car{
public abstract int seat() ;
}
public class SportsCar extends Car{
public int seat()
{
int seat = 2 ;
return seat ;
}
}
public class EconomicCar extends Car{
public int seat()
{
int seat = 4 ;
return seat ;
}
}
Here are the rules of an Abstract class and method:
- Abstract classes cannot be instantiated
- Abstract class can extend an abstract class or a concrete class and implement several interface classes
- Abstract class cannot extend an interface
- If a class contains Abstract method, the class has to be declared Abstract class
- An Abstract class may or may not contain an Abstract method
- Abstract method should not have any code implementations, the sub-classes must override it (sub-class must give the code implementations).
- If a sub-class of an Abstract class does not override the Abstract methods of its super-class, than the sub-class should be declared Abstract also.
- Abstract method cannot be declared with any other non-access modifiers such as static, final, native, transient, volatile
- Abstract classes can only be declared with public and default access modifiers.
- Abstract methods can only be declared with public, default and protected modifier.
Author: Thiagu
No comments:
Post a Comment