Can any body provide me a practical example/scenario where we make use of abstract class and abstract method in Java? An explanation with sample code would be of help in understanding it conceptually. Thanks
-
Look at the Java API: collections, JDBC, I/O, etc. It's littered with abstract classes and interfaces. Those are all the practical examples you should ever need. – duffymo Apr 23 '17 at 12:43
-
Possible duplicate of [Abstract class in Java](http://stackoverflow.com/questions/1320745/abstract-class-in-java) – Gary99 Apr 23 '17 at 15:46
1 Answers
abstract class Car{
public int drivenKm;
//....
public abstract void checkCar();
}
public class Volvo extends Car {
public void checkCar() {
checkWithVolvoTestSpecs1();
}
//you have some Volvo-specific tests implemented here
public void checkWithVolvoTestSpecs1(){
//....
}
}
public class BMW extends Car {
public void checkCar() {
checkWithBMWTest();
}
//you have some BMW-specific tests implemented here
public void checkWithBmWTest(){
//....
}
}
Now you can have a list of Cars containing BMW's or Volvo's.
It sometimes makes no sense to implement a general checkCar()-method, because they need to be checked according to some producer-specific checks. So you should mark the class abstract as well as the method.
Marking the class abstract prevents you from generating a non specific car which can not be checked.
Marking the method abstract is used to not being forced to implement a general car check as well as forcing any derived classes to implement a specific car check.
This grantees that you can call the checkCar()-method for every object in your list of Cars because it is guaranteed that there is no general car object which has no implementation of checkCar() as well as that every specific object (like BMW) in the list has an implementation of that method.
public static void main() {
List<Car> cars = new ArrayList<Car>();
cars.add(new Volvo());
cars.add(new BMW());
foreach(Car c:cars)
c.checkCar();
}

- 442
- 2
- 10