Sie sind auf Seite 1von 20

Page 1 of 20

University of Information
Technology & Sciences
Course Code : IT-203
Course Title : s
Object Oriented Programming Language
Submitted To : Tanzir Mehedi Shawon
Lecturer, Department of IT,UITS
Submitted By : Musharrat Tasnim
ID: 1914555003
Department of IT, UITS
Page 2 of 20

Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires
all the properties and behaviors of a parent object. It is an
important part of OOPs (Object Oriented programming system).

The idea behind inheritance in Java is that you can create new
classes that are built upon existing classes. When you inherit
from an existing class, you can reuse methods and fields of the
parent class. Moreover, you can add new methods and fields in
your current class also.
Page 3 of 20

Inheritance represents the IS-A relationship which is also known


as a parent-child relationship.

Why use inheritance in Java:


 For method overriding (so runtime polymorphism can be
achieved).
 For code Reusability.

Terms used in Inheritance:


 Class: A class is a group of objects which have common
properties. It is a template or blueprint from which objects
are created.
 Sub Class/Child Class: Subclass is a class which inherits
the other class. It is also called a derived class, extended
class, or child class.
 Super Class/Parent Class: Superclass is the class from
where a subclass inherits the features. It is also called a
base class or a parent class.
 Reusability: As the name specifies, reusability is a
mechanism which facilitates you to reuse the fields and
methods of the existing class when you create a new class.
Page 4 of 20

You can use the same fields and methods already defined in
the previous class.

The syntax of Java Inheritance

class Subclass-name extends Superclass-name


{
//methods and fields
}

The extends keyword indicates that you are making a new class
that derives from an existing class. The meaning of "extends" is
to increase the functionality.
Page 5 of 20

In the terminology of Java, a class which is inherited is called a


parent or superclass , and the new class is called child or
subclass.

Java Inheritance Example


Page 6 of 20

As displayed in the above figure, Programmer is the subclass


and Employee is the superclass. The relationship between the
two classes is Programmer IS-A Employee. It means that
Programmer is a type of Employee.

Code:
Page 7 of 20

class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}

Result:
Programmer salary is:40000.0
Bonus of programmer is:10000

Single Inheritance Example


Page 8 of 20

When a class inherits another class, it is known as a single


inheritance. In the example given below, Dog class inherits the
Animal class, so there is the single inheritance.

Example:
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}

Multilevel Inheritance Example


Page 9 of 20

When there is a chain of inheritance, it is known as multilevel inheritance. As you


can see in the example given below, BabyDog class inherits the Dog class which
again inherits the Animal class, so there is a multilevel inheritance.

File: TestInheritance2.java

class Animal{

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

class Dog extends Animal{

void bark(){System.out.println("barking...");}

class BabyDog extends Dog{

void weep(){System.out.println("weeping...");}

class TestInheritance2{

public static void main(String args[]){

BabyDog d=new BabyDog();

d.weep();

d.bark();

d.eat();

}}

Hierarchical Inheritance Example


Page 10 of 20

When two or more classes inherits a single class, it is known as hierarchical


inheritance. In the example given below, Dog and Cat classes inherits the Animal
class, so there is hierarchical inheritance.

File: TestInheritance3.java

class Animal{

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

class Dog extends Animal{

void bark(){System.out.println("barking...");}

class Cat extends Animal{

void meow(){System.out.println("meowing...");}

class TestInheritance3{

public static void main(String args[]){

Cat c=new Cat();

c.meow();

c.eat();

//c.bark();//C.T.Error

}}

Why multiple inheritance is not supported in java?


Page 11 of 20

To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.

Consider a scenario where A, B, and C are three classes. The C class inherits A and
B classes. If A and B classes have the same method and you call it from child class
object, there will be ambiguity to call the method of A or B class.

Since compile-time errors are better than runtime errors, Java renders compile-time
error if you inherit 2 classes. So whether you have same method or different, there
will be compile time error.

class A{

void msg(){System.out.println("Hello");}

class B{

void msg(){System.out.println("Welcome");}

class C extends A,B{//suppose if it were

public static void main(String args[]){

C obj=new C();

obj.msg();//Now which msg() method would be invoked?

Polymorphism in Java
Page 12 of 20

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 example of polymorphism: A person at the same time


can have different characteristic. Like a man at the same time is
a father, a husband, an employee. So the same person posses
different behaviour in different situations. This is called
polymorphism.

Polymorphism is considered as one of the important features of


Object Oriented Programming. Polymorphism allows us to
perform a single action in different ways. In other words,
polymorphism allows you to define one interface and have
multiple implementations. The word “poly” means many and
“morphs” means forms, So it means many forms.

What is polymorphism in programming?


Page 13 of 20

Polymorphism is the capability of a method to do different


things based on the object that it is acting upon. In other words,
polymorphism allows you define one interface and have
multiple implementations. As we have seen in the above
example that we have defined the method sound() and have the
multiple implementations of it in the different-2 sub classes.
Which sound() method will be called is determined at runtime so
the example we gave above is a runtime polymorphism example.

Types of polymorphism and method overloading & overriding


are covered in the separate tutorials. You can refer them here:
1. Method Overloading in Java – This is an example of compile
time (or static polymorphism)
2. Method Overriding in Java – This is an example of runtime
time (or dynamic polymorphism)
3. Types of Polymorphism – Runtime and compile time – This is
our next tutorial where we have covered the types of
polymorphism in detail. I would recommend you to go though
method overloading and overriding before going though this
topic.
Page 14 of 20

The dictionary definition of polymorphism refers to a principle


in biology in which an organism or species can have many
different forms or stages. This principle can also be applied to
object-oriented programming and languages like the Java
language. Subclasses of a class can define their own unique
behaviors and yet share some of the same functionality of the
parent class.

Polymorphism can be demonstrated with a minor modification


to the Bicycle class. For example, a printDescription method
could be added to the class that displays all the data currently
stored in an instance.

public void printDescription(){


System.out.println("\nBike is " + "in gear " + this.gear
+ " with a cadence of " + this.cadence +
" and travelling at a speed of " + this.speed + ". ");
}
To demonstrate polymorphic features in the Java language,
extend the Bicycle class with a MountainBike and a RoadBike
class. For MountainBike, add a field for suspension, which is a
String value that indicates if the bike has a front shock absorber,
Front. Or, the bike has a front and back shock absorber, Dual.
Page 15 of 20

Here is the updated class:

public class MountainBike extends Bicycle {


private String suspension;

public MountainBike(
int startCadence,
int startSpeed,
int startGear,
String suspensionType){
super(startCadence,
startSpeed,
startGear);
this.setSuspension(suspensionType);
}

public String getSuspension(){


return this.suspension;
Page 16 of 20

public void setSuspension(String suspensionType) {


this.suspension = suspensionType;
}

public void printDescription() {


super.printDescription();
System.out.println("The " + "MountainBike has a" +
getSuspension() + " suspension.");
}
}
Note the overridden printDescription method. In addition to the
information provided before, additional data about the
suspension is included to the output.

Next, create the RoadBike class. Because road or racing bikes


have skinny tires, add an attribute to track the tire width. Here is
the RoadBike class:
Page 17 of 20

public class RoadBike extends Bicycle{


// In millimeters (mm)
private int tireWidth;

public RoadBike(int startCadence,


int startSpeed,
int startGear,
int newTireWidth){
super(startCadence,
startSpeed,
startGear);
this.setTireWidth(newTireWidth);
}

public int getTireWidth(){


return this.tireWidth;
}

public void setTireWidth(int newTireWidth){


Page 18 of 20

this.tireWidth = newTireWidth;
}

public void printDescription(){


super.printDescription();
System.out.println("The RoadBike" + " has " +
getTireWidth() +
" MM tires.");
}
}
Note that once again, the printDescription method has been
overridden. This time, information about the tire width is
displayed.

To summarize, there are three classes: Bicycle, MountainBike,


and RoadBike. The two subclasses override the printDescription
method and print unique information.

Here is a test program that creates three Bicycle variables. Each


variable is assigned to one of the three bicycle classes. Each
variable is then printed.
Page 19 of 20

public class TestBikes {


public static void main(String[] args){
Bicycle bike01, bike02, bike03;

bike01 = new Bicycle(20, 10, 1);


bike02 = new MountainBike(20, 10, 5, "Dual");
bike03 = new RoadBike(40, 20, 8, 23);

bike01.printDescription();
bike02.printDescription();
bike03.printDescription();
}
}
The following is the output from the test program:

Bike is in gear 1 with a cadence of 20 and travelling at a speed


of 10.
Page 20 of 20

Bike is in gear 5 with a cadence of 20 and travelling at a speed


of 10.
The MountainBike has a Dual suspension.

Bike is in gear 8 with a cadence of 40 and travelling at a speed


of 20.
The RoadBike has 23 MM tires.

The Java virtual machine (JVM) calls the appropriate method


for the object that is referred to in each variable. It does not call
the method that is defined by the variable's type. This behavior
is referred to as virtual method invocation and demonstrates an
aspect of the important polymorphism features in the Java
language.

Das könnte Ihnen auch gefallen