Abstract Classes in Java

An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.

Why to make a class if you can’t make objects out of it?

Because no one would create a generic, abstract Car object as they would not be able to initialize its state like color, price, model etc.,

And programmers need to instantiate actual car types (derived types) such as HondaCar  and  ToyotaCar .

package com.sneppets.corejava;

public abstract class Car {

	//declare fields
	private double price;
	private String model;
	private String color;
	private String year;

	//declare abstract methods
	public abstract void goFast();
	public abstract void goSlow();
	
}

The above code will compile fine. However when you try to instantiate, you will get compile error like the following

class Car is an abstract class. It can't be instantiated.
Car objCar = new Car();
1 error
Note:
  • An abstract  class has a protected  constructor by default.
  • The methods marked abstract ends with semicolon and will not have an implementation. Such methods are called abstract methods.
  • Even if single method is abstract , then the whole class must be declared abstract . However, you can put non-abstract methods in abstract class.
  • By having non-abstract methods in an abstract class, you are providing inherited method implementations to all its concrete subclasses. Concrete subclasses need to implement only the methods that are abstract.
  • You can’t mark a class both abstract  and final . They both have nearly opposite meanings. An abstract class must be subclassed, whereas a final class must not be subclassed.
Creating concrete subclass
package com.sneppets.corejava;

public class HondaCar extends Car{

	@Override
	public void goFast() {
		System.out.println("Honda-Car driving at 168 MPH");
		
	}

	@Override
	public void goSlow() {
		System.out.println("Honda-Car driving at 10 MPH");		
	}

}
Exam Watch:

If you see the combination of abstract  and final  modifiers used in your code, the code will result in compile error.

guest
0 Comments
Inline Feedbacks
View all comments