What is inheritance in Java with practical example?
What is inheritance in Java with practical example?
I'd be happy to explain inheritance in Java along with a practical example!
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows one class to inherit the properties and behavior of another class. In other words, a child class inherits all the attributes and methods from a parent or superclass. This mechanism enables code reuse, promotes hierarchical relationships between classes, and facilitates the creation of complex hierarchies.
In Java, inheritance is achieved by using the extends
keyword followed by the name of the superclass in the child class's declaration.
Let's consider a practical example to illustrate this concept:
Suppose we have a banking system where we need to create different types of accounts (e.g., savings, checking, and investment). We can use inheritance to define a base class Account
that provides common attributes and methods for all types of accounts, and then inherit from it to create specific account classes.
Here's the code:
// Base class: Account
public abstract class Account {
private String accountNumber;
private double balance;
public Account(String accountNumber) {
this.accountNumber = accountNumber;
this.balance = 0.0;
}
public void deposit(double amount) {
balance += amount;
}
public void withdraw(double amount) {
if (balance >= amount)
balance -= amount;
else
System.out.println("Insufficient funds!");
}
public String getAccountNumber() {
return accountNumber;
}
public double getBalance() {
return balance;
}
}
// Child class: SavingsAccount
public class SavingsAccount extends Account {
private double interestRate;
public SavingsAccount(String accountNumber, double interestRate) {
super(accountNumber);
this.interestRate = interestRate;
}
public void addInterest() {
balance += (balance * interestRate / 100);
}
}
// Child class: CheckingAccount
public class CheckingAccount extends Account {
private int overdraftLimit;
public CheckingAccount(String accountNumber, int overdraftLimit) {
super(accountNumber);
this.overdraftLimit = overdraftLimit;
}
public void withdraw(double amount) {
if (balance + amount <= overdraftLimit)
balance -= amount;
else
System.out.println("Overdraft limit exceeded!");
}
}
In this example:
TheAccount
class is the superclass or parent class that defines common attributes and methods for all types of accounts. The SavingsAccount
and CheckingAccount
classes are subclasses or child classes that inherit from the Account
class.
By using inheritance, we've achieved code reuse:
TheSavingsAccount
class inherits the deposit
, withdraw
, getAccountNumber
, and getBalance
methods from the Account
class. The CheckingAccount
class also inherits these same methods from the Account
class.
We can now create instances of these child classes, which automatically inherit the attributes and methods from the parent class. For example:
SavingsAccount savings = new SavingsAccount("12345", 2.0);
savings.deposit(100); // works because it's inherited from Account
savings.addInterest(); // unique to SavingsAccount
CheckingAccount checking = new CheckingAccount("67890", 500);
checking.deposit(200); // works because it's inherited from Account
checking.withdraw(300); // overrides the withdraw method specific to CheckingAccount
In this example, we've demonstrated how inheritance enables code reuse and facilitates the creation of complex hierarchies in Java.
What is the scenario of inheritance in Java?
I'd be happy to respond in English for you!
Inheritance is one of the fundamental concepts in object-oriented programming (OOP), and it plays a vital role in Java programming language as well.
Scenario:
Imagine you're a software developer tasked with building an e-commerce platform that sells various types of cars. You want to create a class hierarchy that represents different car models, each with its own characteristics (e.g., color, price, speed). One way to achieve this is by using inheritance in Java.
Let's suppose you have a base class called "Car" that defines common attributes and behaviors shared among all car models. This class can serve as the parent or superclass for other specific car classes.
public abstract class Car {
protected String color;
protected int price;
public void startEngine() {
// code to start engine
}
}
Now, you want to create a class that represents a Toyota Corolla. Since it's a type of car, it inherits the attributes and behaviors from the "Car" superclass.
public class ToyotaCorolla extends Car {
public ToyotaCorolla(String color, int price) {
this.color = color;
this.price = price;
}
}
By using inheritance, you've created a new class ("ToyotaCorolla") that inherits the properties and methods from the "Car" superclass. This means that any attributes or behaviors defined in the "Car" class are automatically available to the "ToyotaCorolla" class.
You can create more car models like this (e.g., Ford Mustang, Honda Civic), each inheriting from the "Car" superclass. This promotes code reuse and simplifies your programming task.
Benefits of inheritance:
Code Reuse: By inheriting properties and methods from a parent class, you don't have to duplicate code or define identical logic in multiple classes. Encapsulation: Inheritance helps encapsulate common attributes and behaviors, making it easier to manage complex relationships between classes. Polymorphism: You can create instances of the child classes (e.g., ToyotaCorolla) that behave like their parent class (Car), but with additional unique characteristics.In summary, inheritance in Java is a powerful mechanism for creating hierarchies of related classes, promoting code reuse and simplifying your programming tasks. It allows you to define common attributes and behaviors in a parent class and then specialize those properties and behaviors in child classes, leading to more organized, maintainable, and efficient software development.
I hope that helps!