0% found this document useful (0 votes)
37 views61 pages

MZ Chapter - 3 - Inheritance and Interfaces Part One Oop

Inheritance and Interfaces Part One Oop

Uploaded by

kidus seyoum
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views61 pages

MZ Chapter - 3 - Inheritance and Interfaces Part One Oop

Inheritance and Interfaces Part One Oop

Uploaded by

kidus seyoum
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 61

Chapter Three

Inheritance and Polymorphism


Outline
3.1. Inheritance
3.2. Casting
3.3. Method Overriding and Overloading
3.4. Polymorphism
3.5. Super
3.6. The Object Class
3.7. Abstract Classes
3.8. Interfaces
3.9. Using Interfaces
3.1 Concepts of Inheritance
 Inheritance, which is a form of software reuse in which a new

class is created by absorbing an existing class’s members and

embellishing them with new or modified capabilities.

 When creating a class, rather than declaring completely new

members, you can designate that the new class should inherit the

members of an existing class.

 The existing class is called the superclass | base class | parent

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

3. Modularity: Inheritance can help to organize code into


logical modules. By creating a hierarchy of related
classes, developers can group related functionality
together and encapsulate it in a single module.
4. Extensibility: Inheritance allows for easy extensibility of
existing code. New classes can be created that inherit
properties and methods from an existing class, but then
add new functionality or behaviour.
– Syntax of Java inheritance

class SubClassName extends


SuperClassName {
// Fields and Methods

}
The extends keyword indicates that you are making a new
class that derives from an existing class.
Java Inheritance Example
Employee  Programmer is the subclass and
Employee is the superclass.
firstName: String
lastName: String
Salary: float  The relationship between the two
classes is Programmer IS-A Employee.

 Witch means programmer is a type of


Employee.
Programmer

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,

 the set of objects represented by a superclass is


often larger than the set of objects represented by
any of its subclasses.
Example university member hierarchy
 Each arrow in the hierarchy represents an is-a
relationship.
 As we follow the arrows upward in this class hierarchy,
we can state, that “an Employee is a
CommunityMember” and “a Teacher is a Faculty
member.”
 CommunityMember is the direct superclass of
Employee, Student and Alumnus and is an indirect
 Starting from the bottom, you can follow the
arrows and apply the is-a relationship up to the
topmost superclass.
 For example, an Administrator is a Faculty
member, is an Employee, is a CommunityMember
and, of course, is an Object.
Example Shape Hierarchy
Protected Members
 A class’s public members are accessible wherever the
program has a reference to an object of that class or one
of its subclasses.
 A class’s private members are accessible only within
the class itself.
 Using protected access offers an intermediate level of
access between public and private.
 A superclass’s protected members can be accessed by
 All public and protected superclass members retain

their original access modifier when they become


members of the subclass.
 Public members of the superclass become public

members of the subclass, and protected members of


the superclass become protected members of the

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 in which the subclass constructor,

 Before performing its own tasks(i.e. subclass),

invokes its direct superclass’s constructor either

explicitly via the super reference or implicitly by

calling the superclass’s default constructor or no-

argument constructor.
Constructors in Subclasses cont.
 Similarly, if the superclass is derived from another class
as if, of course, every class except Object, the
superclass constructor invokes the constructor of the
next class up the hierarchy, and so on.
 The last constructor invoked in the chain is always the
constructor for class Object.
 The original subclass constructor’s body finishes
executing last.
Output
Constructors’ Rules in Inheritance
- If we have only default constructor in the parent class,
o We can avoid using supper call in child class; So, no need
to have any constructor in child class.
o The supper class default constructor will always be invoked
when object of child class is created implicitly default
constructor of child class.
Rule Conn…
- If we have only parametrized constructor in supperclass two
things are must.
– 1st it is must to have constructor in child class
– 2nd it is must to use supper call in all subclass’ constructors
• We cannot use two supper call in one constructor.
32

• And supper call must be the first line in child constructor


Using this() and supper()
 Usage of this keyword
1. Can be used to refer current class instance variable

2. This can be used to invoke current class method implicitly.

3. this() can be used to invoke current class constructor.

 The this keyword can be used to refer current class


instance variable.
 If there is ambiguity between the instance variable and
parameters, this keyword resolves the problem of ambiguity
using this()

Output
• this to invoke current class method

• 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
 The this() constructor
call can be used to
invoke the current class
constructor. It is used to
reuse the constructor
3.2 Casting Objects
 Assigning one data type to another or one object
to another is known as casting.
 Java supports two types of casting
a. Data type casting
b. Object casting
 A cast, instructs the compiler to change the
existing type of an object reference to
another type.
 An attempt to cast an object to an incompatible
object at run time will results in a
ClassCastException.
Conditions of assigning objects of different
classes
1. Subclass object can be assigned to a superclass reference
and this casting is done implicitly.
– This is know as upcasting(upwards in the hierarchy from subclass to super
class)

2. Java does not allow to assign super class object to a


subclass reference implicitly.
 Object is data type of the class from which it was instantiated
 Eg. Student s1 = new Student (); //s1 is of type student

 Here student is declared from person and object


 Therefore, a student is a person and is also an object and it can be used
whenever a person or objects are called for.
 The reverse is not necessarily true; a person maybe a student but, it is not
necessarily true because, it can be employee or other similar, an object
maybe a person or a student, but it is not necessarily.
Example
Person p1 = new Person(); //p1 is of type person
Student s1 = new Student(); //s1 is of type student

Object obj = new Student ();

The obj is both an object and student. This is implicit casting


• If we write Student s5 = obj; // This statement will generate compile time
error, because obj is not known to the compiler to be student. (It is known as
Object).
• However, we can tell the compiler that we promise to assign a student to obj by
explicit casting.
Student s5 = (Student)obj; // this is okObject
Obj = new Object (); // this is possible
Student S5 = (Student)obj; // this is not possible.
if (obj instanceof Student)
{ instanceof Student)
if (obj
{ Student S5 = (Student) obj;
} Student S5 = (Student) obj;
Person P1 = new } Student (); Student S1 = n
if(P1 instanceof Student) { } //True if(S1 instanceo
Person P1 = new Student (); Student S1 = new Student ();
if (P1 instanceof Person) { } // True Person P1 = n
if(P1 instanceof Student) { } //True if(S1 instanceof Person) { ….} // True
if (P1 instance
if (P1 instanceof Person) { } // True Person P1 = new Person();
if (P1 instanceof Student) { …}// False
 To assign superclass to subclass
we need explicit casting.
 This is known as downcasting
which requires explicit conversion.
Method Overloading
• If a class has multiple methods having same name
but different in parameters, it is known as Method
Overloading.
• Method overloading increases the readability of the
program.
• The two ways of method overloading
– By changing number of arguments
– By changing the data type of the parameters
Method Overloading example: By changing
parameter type

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));
}
}
3.3 Method Overriding
 Declaring a method in subclass which is already present in
parent class is known as Method overriding.
 When overriding is done a child class give its own
implementation to a method which is already provided by the
parent class.
 In this case ,

 the method in child class is called overriding method and

 the method in super class is called overridden method.


3.3 Method Overriding cont.
 If the same method presents in both super class and
subclass, the method in the subclass overrides the
superclass method.
 This concept in java is known as method overriding

 When overriding is done a child class gives its own


implementation to a method which is already
provided by the parent class.
Overriding

Super keyword is used


to access the super
class /overridden
method eat()

Output

Sub class object


accessing the
overriding method
eat()
 The purpose of Method Overriding is clear here. Child
class wants to give its own implementation.
 The main advantage of method overriding is that
the class give its own specific implementation to an
inherited method without even modifying the
parent class code.
Rules of Method Overriding in Java
 Both the superclass and the subclass methods must have
the same method name, return type and parameter list
and sequences.
 We cannot override methods declared as final and static.
 We should always override abstract methods of superclass.
 Access modifier of the overriding method(subclass) can not
be more restrictive than the overridden method of parent
class. Example: If the superclass method is declared public,
then the overriding method in the subclass cannot be either
Rules of Method Overriding cont.
• A method declared static cannot be overridden but can
be re-declared.
• If a method cannot be inherited, then it cannot be
overridden.
• A subclass within the same package as the instance's
superclass can override any superclass method that is not
declared private or final.
• A subclass in a different package can only override the
non-final methods declared public or protected.
• Constructors cannot be overridden.
}
class CBE extends Bank { //Creating child
classes.
double getRateOfInterest() {return 7.0;}
}
class NIB extends Bank {
double getRateOfInterest(){return 7.5;}
}
class DAB extends Bank {
double getRateOfInterest(){return 7.2;}
}
class BankTest{ //Test class to create objects and call the
methods
public static void main(String args[]){
CBE c=new CBE();
NIB n=new NIB();
DAB a=new DAB();
System.out.println("CBE Rate of Interest: " +
c.getRateOfInterest());
System.out.println("NIB Rate of Interest: " +
n.getRateOfInterest());
System.out.println("DAB Rate of Interest: " +
The Super Keyword
• Previously we saw that the same method in the subclass overrides
the method in superclass.

• In such a situation, the super keyword is used to call the method of


the parent class from the method of the child class.

• 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 used in many context.
 Final can be:
 Variable
 Method
 Class

 Java final keyword


• Stop value change
• Stop method overriding
• Stop inheritance
Java final variable

 If you make any


variable final,
you cannot
change the value
of final variable(it
will be constant)
Java final Method
• If you make any
method final, you
cannot override it.

You might also like