MZ Chapter - 3 - Inheritance and Polymorphismpart Full Oop
MZ Chapter - 3 - Inheritance and Polymorphismpart Full Oop
members, you can designate that the new class should inherit the
class, and the new class is the subclass | derived class | child
class.
Inheritance cont.
A subclass can add its own fields and methods.
The subclass exhibits the behaviors of its superclass
and can modify those behaviors so that they operate
appropriately for the subclass.
This is why inheritance is sometimes referred to as
specialization.
The direct superclass is the superclass from which the
subclass explicitly inherits.
An indirect superclass is any class above the direct
superclass in the class hierarchy, Which defines the
inheritance relationships between classes.
In Java, all classes are part of a class hierarchy that begins with the
Object class, which is defined in the java.lang package
The Object class is the root of the Java class hierarchy, and it defines
the basic behaviour and methods that are common to all objects
in Java.
Every class in Java implicitly inherits from the Object class, either
directly or indirectly.
If a class does not explicitly extend any other class, it automatically
extends the Object class. This means that every class in Java has access
to the methods and fields defined in the Object class, such as getClass(),
equals(), and hashCode().
Generalization and Specialization
– Inheritance represents the IS-A relationship which is also
known as a parent-child relationship.
• When a class represents the shared
characteristics of more than one class, it is
called a generalization; for example,
Vehicle is a generalization of Bike, Car,
and Truck.
• Similarly, when a class represents a
special instance of a general class, it is called a
specialization, so a Car is a
Why we use inheritance in java
1.Code reuse: Inheritance allows developers to reuse code from
existing classes, reducing the amount of code that needs to be
written. By inheriting properties and methods from a superclass, a
subclass can reuse and build upon the functionality of the
superclass without having to duplicate code.
2.Polymorphism: Inheritance is a key component of polymorphism,
which is the ability of objects to take on different forms.
Inheritance allows objects to inherit properties and methods from a
superclass, but then customize or override them as needed. This
flexibility allows developers to create objects with different
Why we use inheritance in java
Bonus: float
class Employee{ public class ProgrammerDemo extends Employee {
float bonus;
String firstName;
String specialty;
String lastName; public String getSpecialty() {
int age; return specialty;
float salary; }
public String getFirstName() { public void setSpecialty(String specialty) {
return firstName; this.specialty = specialty;
}
}
public void setFirstName(String firstName) { public float getBonus() {
this.firstName = firstName; return bonus;
} }
public String getLastName() { public void setBonus(float bonus) {
return lastName; this.bonus = bonus;
}
}
static void print(ProgrammerDemo prog){
public void setLastName(String lastName) { System.out.println(prog.getFirstName()+"\t"+
this.lastName = lastName; prog.getLastName()+"\t"+
} prog.getSpeciality()+"\t"+
public int getAge() { prog.getAge()+"\t"+
return age; prog.getSalary()+"\t"+
prog.getBonus());
}
}
public void setAge(int age) { public static void main(String[] args) {
this.age = age; ProgrammerDemo pObj = new ProgrammerDemo();
} pObj.setFirstName(“Dawit");
public float getSalary() { pObj.setLastName("Dagim");
return salary; pObj.setSpeciality("Mobile");
pObj.setAge(32);
}
pObj.setSalary(23,000);
public void setSalary(float salary) { pObj.setBonus(3,000);
this.salary = salary; print(pObj);
} }
} }
Types of inheritance in java
– On the bases of class, there can be three types of
inheritance in java
Hierarchical Inheritance
Multiple inheritance is not supported in java through class.
However, we can achieve multiple inheritance using
interfaces.
Hierarchical Inheritance example
Superclasses and Subclasses
Often, an object of one class is an object of another class as well.
Super classes tend to be “more general” and subclasses
“more specific”.
For example, a CarLoan is a Loan as are
HomeImprovementLoans and MortageLoans.
Thus, in Java, class CarLoan can be said to inherit from class
Loan.
In this context, class Loan is a superclass and class CarLoan is a
subclass.
Because every subclass object is an object of
its superclass, and one superclass can have
many subclasses,
subclass.
A superclass’s private members are not accessible
outside the class itself.
Rather, they’re hidden in its subclasses and can be
accessed only through the public or protected
methods inherited from the superclass.
Constructors in Subclasses
Instantiating a subclass object begins a chain of
constructor calls.
Output
Using this() cont.
• You may invoke the method of the current class by using the this keyword.
• If you don’t use the this keyword, compiler automatically adds this keyword
while invoking the method.
this(): to invoke
current class
constructor
class Adder{
static int add(int a, int b) {return a+b;}
static double add(double a, double b){return a+b;}
}
class AdderOverloadingTest{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.5,12.5));
}
}
Method Overloading example: By changing number
of arguments
class Adder {
static int add(int a, int b) {
return a + b;
}
static int add(int a, int b, int c){
return a + b + c;
}
}
public class AdderOverloadingTest {
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}
}
public class MyClass {
public int add(int a, int b) {
return a + b;
}
Output
• Syntax
super.methodName();
Using
class Animal {
super
public void move() {
System.out.println("Animals can move");
}
}
class Dog extends Animal {
public void move() {
super.move(); // invokes the super class
method
Super System.out.println("Dogs can walk and run");
Class }
Method }
public class TestDog {
Call public static void main(String args[]) { Animal
Animal b = new Dog(); referenc
b.move(); // runs the method in Dog class e
}
}
Using
super
Final Classes and Final Methods
The final keyword in java is used to restrict the user. The java keyword can be
Variable
Method
Class
• Stop inheritance
Java final variable
• Any Java object that can pass more than one IS-A
test is considered to be polymorphic.
Output
• Here, we instantiate two Salary objects. One using a Salary reference s,
and the other using an Employee reference e.
• When you instantiate a Salary object using a Salary reference s and invoke
s.mailCheck(), the compiler resolves mailCheck() to the version in the Salary
class at compile time, and the JVM invokes the mailCheck() method in the
Salary class at runtime. This is straightforward because you are using a
reference of the same type as the object.
• Key Points:
– An abstract class has no use until it is extended by
some other class.
– If you declare an abstract method in a class then you
must declare the class abstract as well.
– It can have non-abstract method as well.
Abstract Method
Abstract method has no body(it is only prototype).
Always end the declaration with a semicolon(;)
An abstract class must be extended and in same way
abstract method must be overridden.
A class must be declared abstract to have abstract
methods.
Interface
• Understand Interface concept
• Extend an interface
• Implement an interface
Multiple inheritance and interfaces
Multiple inheritance is not supported in java through class.
When one class inherits multiple classes, it is known as multiple
inheritance. For example
Interfaces
In Java, an interface is a blueprint for a class that defines a set
of abstract methods (methods without a body) and,
optionally, constants (public, static, final fields) that
implementing classes must provide concrete implementations
for the abstract methods.
Interfaces allow you to define a contract that classes must
adhere to, ensuring that they implement specific methods
and constants.
Abstract class which is used for achieving partial
Why Interface?
Full abstraction: all methods in an interface are abstract
• In this Vehicle interface, we've defined four abstract methods: start(), stop(),
accelerate(), and brake().
• Any class that implements this interface must provide concrete implementations
for these methods.
• You can then have various classes like Car, Bicycle, Motorcycle, etc., implement
Example cont.
public class Car implements Vehicle {
@Override @Override
public void stop() { public void stop() {
System.out.println("Bicycle stopped"); System.out.println("Motorcycle stopped");
} }
@Override @Override
public void accelerate() { public void accelerate() {
System.out.println("Bicycle is pedaling System.out.println("Motorcycle is revving
faster"); up");
} }
@Override @Override
public void brake() { public void brake() {
System.out.println("Bicycle is using the System.out.println("Motorcycle is
brakes"); braking");
} }
} }
Interface and
Inheritance
An interface can not
implement another
interface. It has to
extend the other
interface.
Key points about interface