Inheritance 1
Inheritance 1
• // Superclass
• class Animal {
• void eat() {
• System.out.println("Animal is eating.");
• }
• }
• dog.eat();
• dog.bark();
• cat.meow();
• }
• }
Real-life scenario where we can model objects using
inheritance.
Explanation:
Common Properties and Behaviors: All employees share common properties like name, employeeID,
and salary. They also have common behaviors like work and getPaid.
Specific Roles and Characteristics: Different types of employees have specific roles and characteristics.
For instance, you may have regular employees, managers, and executives. Managers can approve
leaves, and executives can make strategic decisions.
Using inheritance, you can create a superclass called Employee that contains the common properties
and behaviors:
• class Employee {
• class Manager extends Employee {
• String name;
• void approveLeaveRequest() {
• int employeeID;
• // Code to approve leave requests
• double salary;
• }
• }
• void work() {
• // Code to perform work tasks
• class Executive extends Employee {
• }
• void makeStrategicDecision() {
• // Code to make strategic decisions
• void getPaid() {
• }
• // Code to process salary payment
• }
• }
• }
Multi-Level Inheritance
Multi-level inheritance in Java occurs when a class inherits from another class, which
in turn inherits from yet another class. In this type of inheritance, there's a chain of
inheritance relationships where each derived class is based on the class above it.
Syntax
1. public abstract class Shape{
public abstract void Draw( ); // Abstract method
without definition
}
Abstraction in Java
Imagine you have a bank account. In OOP terms, you can encapsulate the bank
account as follows:
Attributes (Data)
• Account Number
• Account Holder Name
• Balance
Methods (Functions)
• Deposit ()
• Withdraw ()
• GetBalance ()
The data (attributes) and the methods (functions) that operate on this data
are bundled together into a class representing a bank account.
Encapsulation ensures that you can't directly access or modify the account
balance without using the provided methods. The methods enforce rules such
as checking for sufficient balance before a withdrawal.
public class BankAccount {
private int accountNumber;
private String accountHolderName;
private double balance;
// Methods
public void introduce() {
System.out.println("Hi, I'm " + name + " and I'm " + age + " years old.");
}
// Using objects
john.introduce(); // Output: Hi, I'm John Doe and I'm 30 years old.
jane.introduce(); // Output: Hi, I'm Unknown and I'm 0 years old.
}
}
double finalBalance = account.getBalance(); // Get the final account balance