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

Oop Fundamentals

The document explains the concept of inheritance in object-oriented programming, particularly in Java, detailing the relationships between superclasses and subclasses. It covers various types of inheritance, including single, multilevel, hierarchical, and multiple inheritance through interfaces, as well as the importance of constructors, method overriding, and polymorphism. Additionally, it provides examples to illustrate these concepts and their practical applications in Java programming.

Uploaded by

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

Oop Fundamentals

The document explains the concept of inheritance in object-oriented programming, particularly in Java, detailing the relationships between superclasses and subclasses. It covers various types of inheritance, including single, multilevel, hierarchical, and multiple inheritance through interfaces, as well as the importance of constructors, method overriding, and polymorphism. Additionally, it provides examples to illustrate these concepts and their practical applications in Java programming.

Uploaded by

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

Terminology

Inheritance is a fundamental Object-Oriented concept


A class can be defined as a "subclass" of another class.
The subclass inherits all data attributes of its superclass
The subclass inherits all methods of its superclass

superclass: Person
- name: String
The subclass can: - dob: Date
Add new functionality
Use inherited functionality
Override inherited functionality
subclass: Employee
- employeeID: int
- salary: int
- startDate: Date
Terminology

•Super Class: The class whose features are inherited is known as


superclass (or a base class or a parent class).
•Sub Class: The class that inherits the other class is known as a subclass
(or a derived class, extended class, or child class). The subclass can add
its own fields and methods in addition to the superclass fields and
methods.

Syntax :

class derived-class extends base-class


{
//methods and fields
}
How is this useful?

Economy of time – When you implement Employee, you already have all
functionality of Person. No need to reimplement
Parameter passing – If you have a function that expects a Person, you
can pass an Employee, and it is still fine.
Fewer special-purpose functions for every type of Person that exists
Container classes (linked lists, binary trees, etc.) can be defined to hold a
Person, and can hold any subclass of Person

superclass: Person
- name: String
- dob: Date

subclass: Employee
- employeeID: int
- salary: int
- startDate: Date
What really happens?

When an object is created using new, the system must


allocate enough memory to hold all its instance variables.
This includes any inherited instance variables

In this example, we can say that an Employee "is a kind of"


Person.
An Employee object inherits all of the attributes and methods of Person

Person Person
- name: String name = "John Smith"
- dob: Date dob = Jan 13, 1954
Employee
name = "Sally Halls"
is a kind of
dob = Mar 15, 1968
Employee employeeID = 37518
- employeeID: int salary = 65000
- salary: int startDate = Dec 15,
- startDate: Date 2000
Inheritance in Java

Inheritance is declared using the "extends" keyword


If inheritance is not defined, the class extends a class called Object

public class Person


{ Person
private String name;
- name: String
- dob: Date
private Date dob;
}

public class Employee extends Person


{ Employee
private int employeID; - employeeID: int
private int salary; - salary: int
private Date startDate; - startDate: Date
}

Employee anEmployee = new Employee();


// derived class
// Java program to illustrate the concept of inheritance
class MountainBike extends Bicycle {
// base class
// the MountainBike subclass adds one more field
class Bicycle {
public int seatHeight;
// the Bicycle class has two fields
// the MountainBike subclass has one constructor
public int gear;
public MountainBike(int gear, int speed, int startHeight)
public int speed;
{
// the Bicycle class has one constructor
// invoking base-class(Bicycle) constructor
public Bicycle(int gear, int speed)
super(gear, speed);
{
seatHeight = startHeight;
this.gear = gear;
}
this.speed = speed;
// the MountainBike subclass adds one more method
}
public void setHeight(int newValue)
// the Bicycle class has three methods
{
public void applyBrake(int decrement)
seatHeight = newValue;
{
}
speed -= decrement;
// overriding toString() method
}
// of Bicycle to print more info
public void speedup(int increment)
public String toString()
{
{
speed += increment;
return (super.toString() + "\n seat height is “ +
}
seatHeight);
// toString() method to print info of Bicycle
}
public String toString()
}
{
return ("No of gears are " + gear + "\n"+ "speed of bicycle
is " + speed);
}
}
// driver class
public class Test {
public static void main(String args[])
{

MountainBike mb = new MountainBike(3, 100, 25);


System.out.println(mb.toString());
}
}

Output:
No of gears are 3
speed of bicycle is 100
seat height is 25
Types of Inheritance

1. Single Inheritance: In single inheritance, subclasses inherit the features of


one superclass. In the image below, class A serves as a base class for the
derived class B.
Single Inheritance - Syntax and Example

class base class


{
.... methods
}
class derivedClass name extends baseClass
{
methods ... along with this additional feature
}
Single Inheritance - Syntax and Example
class Employee { class single_inheritance {
void salary() { public static void main(String args[]) {
System.out.println("Salary= 50000"); Programmer p = new Programmer();
} p.salary(); // calls method of super class
} p.bonus(); // calls method of sub class
class Programmer extends Employee { }
// Programmer class inherits from Employee }
class
void bonus() {
Output:
System.out.println("Bonus=3000");
}
Salary= 50000
} Bonus=3000
Single Inheritance - Example
class Calc{ int divide(int xx , int yy)

int sum(int i , int j) {

{ return xx/yy;

return i+j; }

} public static void main(String args[]) {

int subract(int i , int j) Main c= new Main();

{ System.out.println(c.sum(2,2));

return i-j; System.out.println(c.subract(2,6));

} System.out.println(c.mul(8,9));

} System.out.println(c.divide(2,2));
public class Main extends Calc { }
int mul(int xx , int yy) }
{
O/P?
return xx*yy;

}
class Rectdemo float GetT()
{ {
int le,be; t=(b*h) / 2;
void Sval(int a,int b) return (t);
{ }
le=a; }
be=b; class Main
} {
int GetR() public static void main(String args[])
{ {
return le*be; Tri Tr=new Tri();
} Tr.Sval(40,8);
} Tr.Sdata(10,6);
class Tri extends Rectdemo System.out.println("Area of Rectangle is
{ calculated as :" +Tr.GetR());
float b,h; System.out.println("Area of Triangle is
float t; calculated As :"+Tr.GetT());
void Sdata(int q,int r) }
{ }
b=r;
h=q; O/P?
}
class Library public void display()
{ {
String lname; System.out.println(super.lname+" and
public Library(String m) "+lname);
{ }
lname = m; public static void main(String[] args)
} {
} Main c = new Main("library name","library
public class Main extends Library id");
{ c.display();
String lname; }
public Main(String x1, String x2) }
{
super(x1); //passing argument to
parent class constructor
this.lname = x2;
}
Output:?
class even {
void display()
{
System.out.println(" Even Nos,4 2");
}
}
class odd extends even {
void display()
{
super.display();
System.out.println(" Odd Nos ,1 3");
}
}
class Main {
public static void main(String[] args)
{ Output:?
even e = new odd();
e.display();
}
}
Types of Inheritance

2. Multilevel Inheritance: In Multilevel Inheritance, a derived class will be


inheriting a base class and as well as the derived class also act as the base class
to other class. In the below image, class A serves as a base class for the derived
class B, which in turn serves as a base class for the derived class C.
class Animal class TestInheritance2
{ {
void eat() public static void main(String args[])
{System.out.println("eating..."); {
} BabyDog d=new BabyDog();
} d.weep();
d.bark();
class Dog extends Animal d.eat();
{ }
void bark() }
{System.out.println("barking...");
}
}

class BabyDog extends Dog


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

weeping...
barking...
eating...
class Electronics { public class Tester {
public Electronics(){ public static void main(String[] arguments) {
System.out.println("Class Electronics"); LED led = new LED();
} led.deviceType();
public void deviceType() { led.category();
System.out.println("Device Type: Electronics"); led.display_tech();
} }
} }
class Television extends Electronics {
public Television() {
System.out.println("Class Television");
} Output:?
public void category() {
System.out.println("Category - Television");
}
}
class LED extends Television {
public LED() {
System.out.println("Class LED");
}
public void display_tech() {
System.out.println("Display Technology- LED");
}
}
Types of Inheritance

3. Hierarchical Inheritance: In Hierarchical Inheritance, one class serves as


a superclass (base class) for more than one subclass.
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
{ Output:?
public static void main(String args[])
{
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}
}
Types of Inheritance

4. Multiple Inheritance (Through Interfaces): In Multiple inheritances, one


class can have more than one superclass and inherit features from all parent
classes. Please note that Java does not support multiple inheritances with
classes. In java, we can achieve multiple inheritances only through Interfaces.
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?
}
}
Output:
Compile Time Error
Types of Inheritance

5. Hybrid Inheritance(Through Interfaces): It is a mix of two or more of the


above types of inheritance. Since java doesn’t support multiple inheritances
with classes, hybrid inheritance is also not possible with classes. In java, we can
achieve hybrid inheritance only through Interfaces.
Inheritance Hierarchy

Each Java class has one (and only one) superclass.


C++ allows for multiple inheritance

Inheritance creates a class hierarchy


Classes higher in the hierarchy are more general and more abstract
Classes lower in the hierarchy are more specific and concrete
There is no limit to the Class
number of subclasses a class
can have Class Class Class

There is no limit to the depth


Class Class Class
of the class tree.

Class
The class called Object

At the very top of the inheritance tree is a class called Object


All Java classes inherit from Object.
All objects have a common ancestor
This is different from C++

The Object class is defined in the java.lang package


Examine it in the Java API Specification

Object
Constructors and Initialization

Classes use constructors to initialize instance variables


When a subclass object is created, its constructor is called.
It is the responsibility of the subclass constructor to invoke the
appropriate superclass constructors so that the instance variables
defined in the superclass are properly initialized

Superclass constructors can be called using the "super"


keyword in a manner similar to "this"
It must be the first line of code in the constructor
If a call to super is not made, the system will automatically
attempt to invoke the no-argument (default) constructor of the
superclass.
Constructors - Example
public class BankAccount
{
private String ownersName;
private int accountNumber;
private float balance;

public BankAccount(int anAccountNumber, String aName)


{
accountNumber = anAccountNumber;
ownersName = aName;
}
}

public class OverdraftAccount extends BankAccount


{
private float overdraftLimit;

public OverdraftAccount(int anAccountNumber, String aName, float aLimit)


{
super(anAccountNumber, aName);
overdraftLimit = aLimit;
}
}
Method Overriding

Subclasses inherit all methods from their superclass


Sometimes, the implementation of the method in the superclass does
not provide the functionality required by the subclass.
In these cases, the method must be overridden.

To override a method, provide an implementation in the


subclass.
The method in the subclass MUST have the exact same signature as
the method it is overriding.
Method overriding - Example

public class BankAccount


{
private String ownersName;
private int accountNumber;
protected float balance;

public void deposit(float anAmount)


{
if (anAmount>0.0)
balance = balance + anAmount;
}

public void withdraw(float anAmount)


{
if ((anAmount>0.0) && (balance>anAmount))
balance = balance - anAmount;
}

public float getBalance()


{
return balance;
Method overriding - Example

public class OverdraftAccount extends BankAccount


{
private float limit;

public void withdraw(float anAmount)


{
if ((anAmount>0.0) &&
(getBalance()+limit>anAmount))
balance = balance - anAmount;
}

}
Object References and Inheritance

Inheritance defines "a kind of" relationship.


In the previous example, OverdraftAccount "is a kind of" BankAccount

Because of this relationship, programmers can "substitute"


object references.
A superclass reference can refer to an instance of the superclass OR an
instance of ANY class which inherits from the superclass.

BankAccount anAccount = new BankAccount(123456, "Craig");

BankAccount account1 = new OverdraftAccount(3323, "John", 1000.0);

BankAccount
anAccount name = "Craig"
accountNumber = 123456
OverdraftAccount
name = "John"
accountNumber = 3323
account1
limit = 1000.0
Polymorphism

In the previous slide, the two variables are defined to have


the same type at compile time: BankAccount
However, the types of objects they are referring to at runtime are
different

What happens when the withdraw method is invoked on each


object?
anAccount refers to an instance of BankAccount. Therefore, the
withdraw method defined in BankAccount is invoked.
account1 refers to an instance of OverdraftAccount. Therefore, the
withdraw method defined in OverdraftAccount is invoked.

Polymorphism is: The method being invoked on an object is


determined AT RUNTIME and is based on the type of the
object receiving the message.
Polymorphism

There are two types of polymorphism in Java:


compile-time polymorphism
runtime polymorphism.
We can perform polymorphism in java by method overloading and
method overriding.

Runtime polymorphism or Dynamic Method Dispatch is a process


in which a call to an overridden method is resolved at runtime rather
than compile-time.

In this process, an overridden method is called through the reference


variable of a superclass. The determination of the method to be called
is based on the object being referred to by the reference variable.
Polymorphism

If the reference variable of Parent class refers to the object of Child


class, it is known as upcasting. For example:

class X{}
class B extends X{}
X a=new B();//upcasting
Polymorphism
class Bike
{
void run()
{
System.out.println("running");}
}
class Activa extends Bike
{
void run()
{
System.out.println("running safely with 60km");
}
public static void main(String args[])
{
Bike b1 = new Activa();//upcasting
Output:
b1.run(); running safely with 60km
}
}
Java Runtime Polymorphism Example: Bank
Consider a scenario where Bank is a class that provides a method to get the
rate of interest. However, the rate of interest may differ according to banks.
For example, SBI, ICICI, and AXIS banks are providing 8.4%, 7.3%, and
9.7% rate of interest.
Java Runtime Polymorphism Example: Bank
class Test
class Bank
{
{
public static void main(String args[])
float getRateOfInterest()
{
{return 0;}
Bank b;
}
b=new SBI();
class SBI extends Bank
System.out.println("SBI Rate of Interest:
{
"+b.getRateOfInterest());
float getRateOfInterest()
b=new ICICI();
{return 8.4f;}
System.out.println("ICICI Rate of Interest:
}
"+b.getRateOfInterest());
class ICICI extends Bank
b=new AXIS();
{
System.out.println("AXIS Rate of Interest:
float getRateOfInterest()
"+b.getRateOfInterest());
{return 7.3f;}
}
}
}
class AXIS extends Bank
{ O/P:
float getRateOfInterest() SBI Rate of Interest: 8.4
{return 9.7f;} ICICI Rate of Interest: 7.3
} AXIS Rate of Interest: 9.7
Java Runtime Polymorphism Example: Shape
class Shape class Test2
{ {
void draw(){System.out.println("drawing..."); public static void main(String args[])
} {
} Shape s;
class Rectangle extends Shape s=new Rectangle();
{ s.draw();
void draw() s=new Circle();
{System.out.println("drawing rectangle..."); s.draw();
} s=new Triangle();
} s.draw();
class Circle extends Shape }
{ }
void draw(){System.out.println("drawing
circle...");
}
}
class Triangle extends Shape
O/P:
{
drawing rectangle...
void draw(){System.out.println("drawing
drawing circle...
triangle...");
drawing triangle...
} }
Java Runtime Polymorphism Example: Animal
class Animal class Test3
{ {
void eat() public static void main(String[] args)
{System.out.println("eating...");} {
} Animal a;
class Dog extends Animal a=new Dog();
{ a.eat();
void eat() a=new Cat();
{System.out.println("eating bread...");} a.eat();
} a=new Lion();
class Cat extends Animal a.eat();
{ }
void eat() }
{System.out.println("eating rat...");}
}
class Lion extends Animal
{ O/P:
void eat() eating bread...
{System.out.println("eating meat..."); eating rat...
} eating meat...
}
Java Runtime Polymorphism: Multilevel Inheritance
class Animal class BabyDog extends Dog
{ {
void eat() void eat()
{ {
System.out.println("eating"); System.out.println("drinking milk");
} }
} public static void main(String args[])
class Dog extends Animal {
{ Animal a1,a2,a3;
void eat() a1=new Animal();
{ a2=new Dog();
System.out.println("eating fruits");} a3=new BabyDog();
} a1.eat();
a2.eat();
a3.eat();
}
}
O/P:
eating
eating fruits
drinking milk
Java Runtime Polymorphism: Multilevel Inheritance
class Animal
{
void eat()
{
System.out.println("animal is eating...");}
}
class Dog extends Animal
{
void eat()
{
System.out.println("dog is eating...");
}
}
class BabyDog1 extends Dog
{
public static void main(String args[])
{
Animal a=new BabyDog1(); O/P:
a.eat(); Dog is eating
}
}
Static Binding and Dynamic Binding
Connecting a method call to the method body is known as binding.
There are two types of binding:
• Static Binding (also known as Early Binding).
• Dynamic Binding (also known as Late Binding).

When type of the object is determined at compiled time(by the compiler), it


is known as static binding.
If there is any private, final or static method in a class, there is static binding.

class Dog
{
private void eat(){System.out.println("dog is eating...");
}
public static void main(String args[])
{
Dog d1=new Dog();
d1.eat();
}
}
Static Binding and Dynamic Binding
When type of the object is determined at run-time, it is known as dynamic
binding.
class Animal{
void eat(){System.out.println("animal is eating...");}
}

class Dog extends Animal{


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

public static void main(String args[]){


Animal a=new Dog();
a.eat();
}
}
Final Methods and Final Classes

• The final keyword in java is used to restrict the user. The java final
keyword can be used in many context. Final can be:
• variable
• method
• class

• final variable that have no value it is called blank final variable or


uninitialized final variable.
• It can be initialized in the constructor only.
• The blank final variable can be static also which will be initialized in the
static block only.

Java final variable: If you make any variable as final, you cannot change the
value of final variable (It will be constant).
Final Methods and Final Classes

class Bike
{
final int slimit=90;//final variable
void run()
{
slimit=400;
}
public static void main(String args[])
{
Bike o=new Bike();
o.run();
}
}

Output: Compile Time Error


Final Methods and Final Classes

Methods can be qualified with the final modifier


Final methods cannot be overridden.
This can be useful for security purposes.

public final boolean validatePassword(String username, String Password)


{
[...]

Classes can be qualified with the final modifier


The class cannot be extended
This can be used to improve performance. Because there an be no
subclasses, there will be no polymorphic overhead at runtime.
public final class Color
{
[...]
Final Methods: Example

class Bike
{
final void run()
{
System.out.println("running");
}
}

class Honda extends Bike


{
void run()
{
System.out.println("running safely with 100kmph");
}
public static void main(String args[])
{
Honda honda= new Honda();
honda.run(); Output: Compile Time Error
}
}
Final Class: Example

final class Bike{}

class Honda extends Bike


{
void run()
{
System.out.println("running safely with 100kmph");
}
public static void main(String args[])
{
Honda h= new Honda();
h.run();
}
}

Output: Compile Time Error


Final Method: Example

class Bike
{
final void run()
{
System.out.println("running...");
}
}
class Honda extends Bike
{
public static void main(String args[])
{
new Honda().run(); Output: running...
}
}

• final method is inherited but you cannot override it.


Examples

class Bike class A


{ {
final int speedlimit;//blank final variable static final int data;//static blank final
Bike() variable
{ static{ data=50;}
speedlimit=70; public static void main(String args[])
System.out.println(speedlimit); {
} System.out.println(A.data);
}
public static void main(String args[]) }
{
new Bike();
}
}

• A final variable that is not initialized at the time of declaration is known as


blank final variable. It can be initialized only in constructor.

• A static final variable that is not initialized at the time of declaration is


known as static blank final variable. It can be initialized only in static block.
Permissions
Modifier Visibility outside class
private None
no modifier Classes in the package
protected Classes in package & all subclasses
public All classes
Review

What is inheritance? What is a superclass? What is a subclass?


Which class is at the top of the class hierarchy in Java?
What are the constructor issues surrounding inheritance?
What is method overriding? What is polymorphism? How are they
related?
What is a final method? What is a final class?

You might also like