Java example of Abstract class and abstract methods and declared abstract
Java Abstract Class Example: Car and Maruti Implementation
Understanding Abstraction in Java
Abstraction is a fundamental concept in object-oriented programming (OOP) that hides the implementation details and exposes only the essential functionalities to the user. It helps in achieving a clean and modular code structure.
Abstraction is a process of hiding the implementation details and showing only functionality to the user.
below is key point to remaimber when you creating abstract class.
Below is an example demonstrating abstract classes and methods in Java. Here, we define an abstract class Car
and implement its methods in the subclass Maruti
.
Car
package com.developer;
abstract class Car {
int reg_no;
// Constructor
Car(int reg) {
reg_no = reg;
}
// Abstract methods
abstract void price(int p);
abstract void braking(int force);
}
Maruti
package com.developer;
class Maruti extends Car {
Maruti(int reg_no) {
super(reg_no);
}
// Implementing abstract methods
void price(int p) {
System.out.println("This shows the price of Maruti car.");
}
void braking(int force) {
System.out.println("Maruti cars use hydraulic brakes.");
}
public static void main(String args[]) {
Maruti m = new Maruti(10);
m.price(7);
m.braking(9);
}
}
This shows the price of Maruti car.
Maruti cars use hydraulic brakes.
In this article, we explored how to implement an abstract class in Java using the Car example and its subclass Maruti.
Using abstraction, we can define common characteristics in a base class and enforce implementation in subclasses, leading to better code maintainability and reusability.
For more Java tutorials, follow us on Instagram and Facebook!
abstract
keyword.