Lab 8 Oop 11112020 013226pm 15122021 094301pm 1 22112022 021509pm
Lab 8 Oop 11112020 013226pm 15122021 094301pm 1 22112022 021509pm
Lab 8 Oop 11112020 013226pm 15122021 094301pm 1 22112022 021509pm
INHERITANCE:
INHERITANCE:
• inheritance: a parent-child relationship between classes
• allows sharing of the behavior of the parent class into its child classes
• one of the major benefits of object-oriented programming (OOP) is this code
sharing between classes through inheritance
Terms used in Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
Ba se c la ss De rive d c la sse s
Student GraduateStudent
UndergraduateStudent
Shape Circle
Triangle
Rectangle
Loan CarLoan
HomeImprovementLoan
MortgageLoan
Employee FacultyMember
StaffMember
Account CheckingAccount
SavingsAccount
Example :single
class Animal{ }
void eat() }
{ class TestInheritance{
System.out.println("eating..."); public static void main(String args[])
} } {
class Dog extends Animal{ Dog d=new Dog();
void bark() d.bark();
{ d.eat();
System.out.println("barking..."); }}
Multilevel Inheritance Example
class Animal{ {
void eat() System.out.println("weeping...");}
{ }
System.out.println("eating..."); class TestInheritance2{
} } public static void main(String args[]){
class Dog extends Animal{ BabyDog d=new BabyDog();
void bark() d.weep();
{ d.bark();
System.out.println("barking..."); d.eat();
} } }}
class BabyDog extends Dog{
void weep()
Hierarchical Inheritance Example
class Animal{ System.out.println("meowing...");
void eat() }
{ }
System.out.println("eating..."); class TestInheritance3{
} } public static void main(String args[]){
class Dog extends Animal{ Cat c=new Cat();
void bark() Dog d = new Dog();
{ d.bark();
System.out.println("barking..."); d.eat();
} } c.meow();
class Cat extends Animal{ c.eat();
void meow() }}
{
The protected Modifier
• The protected modifier allows a member of a base class to be
inherited into a child
• Protected visibility provides more encapsulation than public visibility
does
• However, protected visibility is not as tightly encapsulated as private
visibility
• Protected variables and methods can be shown with a # symbol
preceding them in UML diagrams
SYNTAX
protected void sleep()
{
System.out.println("sleeping");
}
Method overriding
class Vehicle{
Vehicle()
{System.out.println("Vehicle is created");
}}
class Bike5 extends Vehicle{
Bike5()
{
super();//will invoke parent class constructor
System.out.println("Bike is created");
}
public static void main(String args[]){
Bike5 b=new Bike5();
}}
Note: super() is added in each class constructor automatically by compiler.
• super can be used to invoke parent class method The super keyword can
also be used to invoke parent class method. It should be used in case
subclass contains the same method as parent class as in the example given
below:
Task 1:
Write a program in java showing the use of inheritance a follows:
Bahria
Vehicle
Animal