0% found this document useful (0 votes)
9 views42 pages

Inheritance 1

Uploaded by

snikith7
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
9 views42 pages

Inheritance 1

Uploaded by

snikith7
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 42

Single Inheritance: In single inheritance, a subclass inherits from only one superclass.

• // Superclass
• class Animal {
• void eat() {
• System.out.println("Animal is eating.");
• }
• }

• // Subclass inheriting from Animal


• class Dog extends Animal {
• void bark() {
• System.out.println("Dog is barking.");
• }
• }

• public class Main {


• public static void main(String[] args) {
• Dog d1 = new Dog();

• d1.eat(); // Calls the eat method from the Animal class


• d1.bark(); // Calls the bark method from the Dog class
• }

Create a new class, Cat, that also inherits from Animal.
Implement a unique method for Cat and create a
Cat object.
• // New subclass inheriting from Animal
• class Cat extends Animal {
• void meow() {
• System.out.println("Cat is meowing.");
• }
• }

• public class Main {


• public static void main(String[] args) {
• Dog dog = new Dog();
• Cat cat = new Cat(); // Creating a Cat object

• dog.eat();
• dog.bark();
• cat.meow();
• }
• }
Real-life scenario where we can model objects using
inheritance.

• Modeling Employees in an Organization


 In an organization, you have different types of employees, each with
common attributes like a name, employee ID, and salary, but also with
unique attributes and behaviors based on their roles. Inheritance can
help represent this hierarchy efficiently.

 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.

// Base class (parent class)


class Animal {
void eat() {
System.out.println("Animal is eating...");
}
}

// Intermediate class (derived from Animal)


class Mammal extends Animal {
void run() {
System.out.println("Mammal is running...");
}
}
// Derived class (derived from Mammal)
class Dog extends Mammal {
void bark() {
System.out.println("Dog is barking...");
}
}

public class Main {


public static void main(String[] args) {
// Creating an instance of the derived class
Dog myDog = new Dog();

// Calling methods from all three classes


myDog.eat(); // Calls the eat() method from the Animal class
myDog.run(); // Calls the run() method from the Mammal class
myDog.bark(); // Calls the bark() method from the Dog class
}
}
Design a class hierarchy for representing different types of vehicles, such as
"Car," "Motorcycle," and "Truck." Each vehicle should have common
attributes like "make," "model," and "year," and each type should have
specific attributes or behaviors. Implement a simple program that
demonstrates the use of this hierarchy by creating instances of each vehicle
type and accessing their attributes.
 Polymorphism?

• The word polymorphism means having many forms. In simple


words, we can define polymorphism as the ability of a message to
be displayed in more than one form.

 Real-life Illustration Polymorphism: A person at the same time


can have different characteristics. Like a man at the same time is a
father, a husband, and an employee. So the same person
possesses different behavior in different situations. This is called
polymorphism.
 A real-life example of polymorphism can be found in the use of a
remote control for various electronic devices, such as a television, a
DVD player, and a sound system. The remote control serves as a
common interface to interact with different types of devices, even
though each device may have its own unique set of functions and
behaviors.

 The remote control demonstrates polymorphism by providing a


consistent interface for interacting with different electronic devices,
allowing you to perform actions without needing to be aware of the
underlying implementation details of each device. This is a real-world
example of how polymorphism simplifies and streamlines interactions
with diverse objects.
class Animal {
void sound() {
// Base class implementation (can be overridden by subclasses)
}
}

class Dog extends Animal { public class PolymorphismExample {


public static void animalSnd(animal) {
@Override
animal.sound();
void sound() { }
System.out.println(“Dog Sound");
} public static void main(String[] args) { we define a method called
} Animal dog = new Dog(); animalSnd that can be
Animal cat = new Cat(); used to make animals
Animal cow = new Cow(); make sounds. It takes an
class Cat extends Animal {
Animal as input, and
@Override animalSnd(dog); // Animal is like a general
void sound() { animalSnd(cat); // type for any animal.
System.out.println(“Cat Sound!"); animalSnd(cow); }
} }
}

class Cow extends Animal {


@Override
void sound() {
System.out.println(“Cow Sound");
}
}
Abstract Classes

• A class that is declared with abstract keyword, is known as abstract class in


java. It can have abstract and non-abstract methods (method with body).

Syntax
1. public abstract class Shape{
public abstract void Draw( ); // Abstract method
without definition

public void Display( ) {


System.out.println(“Display Method
of Shape class”);
}

}
Abstraction in Java

• Abstraction is a process of hiding the implementation details


and showing only functionality to the user.

• Another way, it shows only important things to the user and


hides the internal details for example sending sms, you just
type the text and send the message. You don't know the
internal processing about the message delivery.

• Abstraction lets you focus on what the object does instead of


how it does it.
Ways to achieve Abstraction
• There are two ways to achieve abstraction in java
• Abstract class (0 to 100%)
• Interface (100%)
Example

public abstract class LivingThing {


public void breath( ){
System.out.println("Living Thing breathing..."); }
public void eat( ){
System.out.println("Living Thing eating..."); }
public abstract void walk( );
}

public class Human extends LivingThing {

public void walk( ){


System.out.println("Human walks..."); }
}
abstract class Animal {
abstract void makeSound(); // Abstract method that must be implemented by subclasses
}

class Dog extends Animal {


@Override
void makeSound() { public class PolymorphismExample {
System.out.println("Dog Sound");
public static void animalSound(animal) {
} animal.makeSound();
} }
we define a method called
class Cat extends Animal { public static void main(String[] args) { animalSnd that can be
@Override Animal dog = new Dog(); used to make animals
Animal cat = new Cat(); make sounds. It takes an
void makeSound() {
Animal cow = new Cow(); Animal as input.
System.out.println("Cat Sound!");
} animalSound(dog); // Output: Dog Sound
} animalSound(cat); // Output: Cat Sound!
animalSound(cow); // Output: Cow Sound
class Cow extends Animal { }
}
@Override
void makeSound() {
System.out.println("Cow Sound");
}
}
Write an abstract class named "Shape"
with an abstract method "calculateArea()."
Ensure that the class provides a
foundation for calculating the area of
different shapes.
abstract class Shape { public Triangle(double base, double height) {
abstract double calculateArea(); this.base = base;
} this.height = height;
}
class Circle extends Shape { @Override
private double radius; double calculateArea() {
return 0.5 * base * height;
public Circle(double radius) { }
this.radius = radius; }
}
class ShapeCalculator {
public static void main(String[] args) {
@Override
Shape circle = new Circle(5.0);
double calculateArea() {
Shape rectangle = new Rectangle(4.0, 6.0);
return Math.PI * radius * radius; Shape triangle = new Triangle(3.0, 8.0);
}
} System.out.println("Area of Circle: " + circle.calculateArea());
System.out.println("Area of Rectangle: " + rectangle.calculateArea());
class Rectangle extends Shape { System.out.println("Area of Triangle: " + triangle.calculateArea());
private double width; }
private double height;
}

public Rectangle(double width, double height) {


this.width = width;
this.height = height;
}
• An abstract class in programming is like a blueprint for
creating related objects.
@Override
double calculateArea() { • The method calculateArea is declared as abstract in the
return width * height; Shape class, which means that all subclasses must
} provide their own implementation for this method. This
} is an example of method overriding in object-oriented
programming.
class Triangle extends Shape {
ENCAPSULATION

 Encapsulation is the concept of bundling data (attributes) and the


methods (functions) that operate on that data into a single unit called
a class.

 Encapsulation helps in hiding the internal implementation details of a


class and exposing a controlled and well-defined interface to the
outside world. This is achieved through the use of access modifiers like
private, protected, and public.
 Real-Life Example: Bank Account

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;

// Constructor to initialize the account


public BankAccount(int accountNumber, String accountHolderName, double initialBalance)
{
this.accountNumber = accountNumber;
this.accountHolderName = accountHolderName;
this.balance = initialBalance;
}

// Method to deposit money into the account


public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposited $" + amount + ". New balance: $" + balance);
} else {
System.out.println("Invalid deposit amount.");
}
}
// Method to withdraw money from the account
public void withdraw(double amount) {
if (amount > 0 && balance >= amount) {
balance -= amount;
System.out.println("Withdrawn $" + amount + ". New balance: $" + balance);
} else {
System.out.println(“Insufficient balance");
}
}

// Method to get the current balance


public double getBalance() {
return balance;
}

// Main method to test the BankAccount class


public static void main(String[] args) {
BankAccount account = new BankAccount(12345,
• In this "John Doe",the
example, 1000.0);
BankAccount class encapsulates
the data (account number, account holder name,
account.deposit(500.0); balance) and provides methods to interact with the
account.
account.withdraw(200.0);
account.withdraw(1500.0); • The private access modifiers ensure that these
} attributes cannot be directly modified from outside
} the class, promoting data integrity and controlled
public class Person {
// Fields (attributes)
private String name;
private int age;

// Constructor with parameters


public Person(String name, int age) {
this.name = name;
this.age = age;
}

// Default constructor (no parameters)


public Person() {
this.name = "Unknown";
this.age = 0;
}

// Methods
public void introduce() {
System.out.println("Hi, I'm " + name + " and I'm " + age + " years old.");
}

public static void main(String[] args) {


// Creating objects using constructors
Person john = new Person("John Doe", 30);
Person jane = new Person(); // Using the default constructor

// 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

System.out.println("Your Account Balance is: $" + finalBalance);


}
}
Method Overloading: Method overloading is the ability to define multiple methods in
the same class with the same name but different parameter lists (i.e., a different
number or types of parameters).

Method Overriding: Method overriding is the ability to provide a new implementation


for a method in a subclass that is already defined in its superclass. The overriding
method has the same name, return type, and parameters as the method in the
superclass.
Method Overloading Method Overriding
class Shape {
class Math { void draw() {
// Method 1: Add two integers System.out.println("Drawing a shape");
public int add(int a, int b) { }
return a + b; }
}
class Circle extends Shape {
@Override
// Method 2: Add three integers
void draw() {
public int add(int a, int b, int c) {
System.out.println("Drawing a circle");
return a + b + c; }
} }

// Method 3: Add two doubles class Square extends Shape {


public double add(double a, double b) { @Override
return a + b; void draw() {
} System.out.println("Drawing a square");
} }
}
public class MethodOverloadingExample {
public static void main(String[] args) {
public class MethodOverridingExample {
public static void main(String[] args) {
Math math = new Math();
Shape shape1 = new Circle();
Shape shape2 = new Square();
int sum1 = math.add(5, 10); // Calls Method 1
int sum2 = math.add(5, 10, 15); // Calls Method 2 shape1.draw(); // Calls Circle's draw() - Polymorphism
double sum3 = math.add(2.5, 3.5); // Calls Method 3 shape2.draw(); // Calls Square's draw() - Polymorphism
}
System.out.println("Sum 1: " + sum1); }
System.out.println("Sum 2: " + sum2);
System.out.println("Sum 3: " + sum3);
}

You might also like