Object Oriented Programming with Java
Unit No. 2: Inheritance and Polymorphism
Sanjivani Rural Education Society’s
Sanjivani College of Engineering, Kopargaon-423603
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
NAAC ‘A’ Grade Accredited, ISO 9001:2015 Certified
Department of Information Technology
(UG Course: NBA Accredited)
Dr. Y.S.Deshmukh
Assistant Professor
Object Oriented Programming with Java
Inheritance:
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.
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.
Object Oriented Programming with Java
Inheritance:
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. You can use the
same fields and methods already defined in the previous class.
Object Oriented Programming with Java
Inheritance:
Object Oriented Programming with Java
Inheritance:
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);
}
}
Object Oriented Programming with Java
Types of inheritance in java
Object Oriented Programming with Java
Types of inheritance in java
Object Oriented Programming with Java
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();
}}
Object Oriented Programming with Java
Multilevel Inheritance Example
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();
}}
Object Oriented Programming with Java
Hierarchical Inheritance Example
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
}}
Object Oriented Programming with Java
Why multiple inheritance is not supported in java?
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.
Object Oriented Programming with Java
Why multiple inheritance is not supported in java?
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?
}
}
Object Oriented Programming with Java
Polymorphism: Method Overloading in Java
If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.
If we have to perform only one operation, having same name of the methods increases the
readability of the program.
Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for
three parameters then it may be difficult for you as well as other programmers to understand
the behavior of the method because its name differs.
Object Oriented Programming with Java
Polymorphism: Method Overloading in Java
Advantage of method overloading
Method overloading increases the readability of the program.
Different ways to overload the method
There are two ways to overload the method in java
• By changing number of arguments
• By changing the data type
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;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
Object Oriented Programming with Java
Polymorphism: Method Overloading in Java
class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
Object Oriented Programming with Java
Polymorphism: Method Overriding in Java
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.
In other words, If a subclass provides the specific implementation of the method that has
been declared by one of its parent class, it is known as method overriding.
Usage of Java Method Overriding
• Method overriding is used to provide the specific implementation of a method which is
already provided by its superclass.
• Method overriding is used for runtime polymorphism
Object Oriented Programming with Java
Polymorphism: Method Overriding in Java
Rules for Java Method Overriding
• The method must have the same name as in the parent class
• The method must have the same parameter as in the parent class.
• There must be an IS-A relationship (inheritance).
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike extends Vehicle{
public static void main(String args[]){
//creating an instance of child class
Bike obj = new Bike();
//calling the method with child class instance
obj.run();
}
}
Object Oriented Programming with Java
Super Keyword in Java
The super keyword in Java is a reference variable which is used to refer immediate parent class object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly which is
referred by super reference variable.
Usage of Java super Keyword
• super can be used to refer immediate parent class instance variable.
• super can be used to invoke immediate parent class method.
• super() can be used to invoke immediate parent class constructor.
Object Oriented Programming with Java
Super Keyword in Java
Object Oriented Programming with Java
1.class Animal{
2.String color="white";
3.}
4.class Dog extends Animal{
5.String color="black";
6.void printColor(){
7.System.out.println(color);//prints color of Dog class
8.System.out.println(super.color);//prints color of Animal cl
ass
9.}
10.}
11.class TestSuper1{
12.public static void main(String args[]){
13.Dog d=new Dog();
14.d.printColor();
15.}}
Object Oriented Programming with Java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}
Object Oriented Programming with Java
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}
Object Oriented Programming with Java
Abstract Classes
A class which is declared with the abstract keyword is known as an abstract class in Java. It can
have abstract and non-abstract methods (method with the body).
Abstraction in Java:
Abstraction is a process of hiding the implementation details and showing only functionality
to the user.
Another way, it shows only essential things to the user and hides the internal details, for
example, sending SMS where you type the text and send the message. You don't know the
internal processing about the message delivery.
Ways to achieve Abstraction:
There are two ways to achieve abstraction in java
Abstract class (0 to 100%)
Interface (100%)
Object Oriented Programming with Java
Abstract Classes
Abstract class in Java
A class which is declared as abstract is known as an abstract class. It can have abstract and
non-abstract methods. It needs to be extended and its method implemented. It cannot be
instantiated.
• An abstract class must be declared with an abstract keyword.
• It can have abstract and non-abstract methods.
• It cannot be instantiated.
• It can have constructors and static methods also.
• It can have final methods which will force the subclass not to change the body of the
method.
Object Oriented Programming with Java
Abstract Classes
Object Oriented Programming with Java
Abstract Methods
A method which is declared as abstract and does not have implementation is known as an
abstract method.
abstract void printStatus();
abstract class A{}
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
Object Oriented Programming with Java
Abstract Classes & Methods:
Abstract class having constructor, data member and methods
An abstract class can have a data member, abstract method, method body (non-abstract
method), constructor, and even main() method.
abstract class Bike{
Bike(){System.out.println("bike is created");}
abstract void run();
void changeGear(){System.out.println("gear changed");}
}
class Honda extends Bike{
void run(){System.out.println("running safely..");}
}
class TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.changeGear();
Object Oriented Programming with Java
Interface in Java:
An interface in Java is a blueprint of a class.
It has static constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body. It is used to achieve abstraction and
multiple inheritance in Java.
In other words, you can say that interfaces can have abstract methods and variables.
It cannot have a method body.
Java Interface also represents the IS-A relationship.
It cannot be instantiated just like the abstract class.
Since Java 8, we can have default and static methods in an interface.
Since Java 9, we can have private methods in an interface.
Object Oriented Programming with Java
Interface in Java:
Why use Java interface?
It is used to achieve abstraction.
By interface, we can support the functionality of multiple inheritance.
It can be used to achieve loose coupling.
Object Oriented Programming with Java
Interface in Java:
Syntax:
interface <interface_name>{
// declare constant fields
// declare methods that abstract
// by default.
}
Object Oriented Programming with Java
Interface in Java:
The relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface extends another
interface, but a class implements an interface.
Object Oriented Programming with Java
Interface in Java:
interface Bank{
float rateOfInterest();
}
class SBI implements Bank{
public float rateOfInterest(){return 9.15f;}
}
class PNB implements Bank{
public float rateOfInterest(){return 9.7f;}
}
class TestInterface2{
public static void main(String[] args){
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}}
Object Oriented Programming with Java
Interface in Java:
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as
multiple inheritance.
Object Oriented Programming with Java
Interface in Java:
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
A7 obj = new A7();
obj.print();
obj.show();
}
}
Object Oriented Programming with Java
Interface in Java:
Multiple inheritance is not supported through class in java, but it is possible by an interface, why?
As we have explained in the inheritance chapter, multiple inheritance is not supported in the case
of class because of ambiguity. However, it is supported in case of an interface because there is no
ambiguity. It is because its implementation is provided by the implementation class. For example:
interface Printable{
void print();
}
interface Showable{
void print();
}
class TestInterface3 implements Printable, Showable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
TestInterface3 obj = new TestInterface3();
obj.print();
}
}
Object Oriented Programming with Java
Java Package:
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined packages.
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
Object Oriented Programming with Java
Java Package:
Object Oriented Programming with Java
Java Package:
Simple example of java package
The package keyword is used to create a package in java.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to compile java package
If you are not using any IDE, you need to follow the syntax given below:
javac -d directory javafilename
javac -d . Simple.java
Object Oriented Programming with Java
Java Package:
The -d switch specifies the destination where to put the generated class file. You can use
any directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you
want to keep the package within the same directory, you can use . (dot).
How to run java package program
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
To Compile: javac -d . Simple.java
To Run: java mypack.Simple
The -d is a switch that tells the compiler where to put the class file i.e. it represents
destination. The . represents the current folder.
Object Oriented Programming with Java
Java Package:
How to access package from another package?
There are three ways to access the package from outside the package.
• import package.*;
• import package.classname;
• fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible
but not subpackages.
The import keyword is used to make the classes and interface of another package
accessible to the current package.
Object Oriented Programming with Java
Java Package:
Example of package that import the packagename.*
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Object Oriented Programming with Java
Java Package:
2) Using packagename.classname
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Object Oriented Programming with Java
Java Package:
3) Using fully qualified name
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Object Oriented Programming with Java
Thank You

More Related Content

PDF
Java conditional statements
PPTX
Basic Concepts of OOPs (Object Oriented Programming in Java)
PPTX
Polymorphism in java
PPTX
Delegates and events in C#
PPTX
Polymorphism in java
PPTX
JAVA UNIT 2
PPTX
Super Keyword in Java.pptx
PPTX
Inheritance in java
Java conditional statements
Basic Concepts of OOPs (Object Oriented Programming in Java)
Polymorphism in java
Delegates and events in C#
Polymorphism in java
JAVA UNIT 2
Super Keyword in Java.pptx
Inheritance in java

What's hot (20)

PDF
Java IO
PPTX
PROGRAMMING IN JAVA unit 1.pptx
PPTX
Var arg methods
PPTX
Classes, objects in JAVA
PPTX
Interfaces and abstract classes
PPTX
Java exception handling
PPTX
Strings in Java
PPT
Abstract class in java
PPTX
History Of JAVA
PPTX
Constructor in java
PPTX
Java Array String
PPTX
Static Members-Java.pptx
ODP
Basic of Java
PDF
Java - File Input Output Concepts
PPTX
Constructors in C++.pptx
PPTX
History of java'
PPTX
Exception Handling in Java
PPTX
Java arrays
PPTX
Classes objects in java
PPTX
Design Patterns - 01 Introduction and Decorator Pattern
Java IO
PROGRAMMING IN JAVA unit 1.pptx
Var arg methods
Classes, objects in JAVA
Interfaces and abstract classes
Java exception handling
Strings in Java
Abstract class in java
History Of JAVA
Constructor in java
Java Array String
Static Members-Java.pptx
Basic of Java
Java - File Input Output Concepts
Constructors in C++.pptx
History of java'
Exception Handling in Java
Java arrays
Classes objects in java
Design Patterns - 01 Introduction and Decorator Pattern
Ad

Similar to Unit No 3 Inheritance annd Polymorphism.pptx (20)

PPTX
OBJECT ORIENTED PROGRAMMING_Unit2_NOTES.pptx
PDF
‏‏‏‏‏‏oop lecture objectives will come.pdf
PPTX
Java - Inheritance_multiple_inheritance.pptx
PDF
11.Object Oriented Programming.pdf
PDF
Java kkdhaksndjsjkanshdjdjdnsnxxhjdjdnxhxjx
PPTX
java_inheritance_oop_20250730110153.pptx
PPTX
Inheritance in Java is a mechanism in which one object acquires all the prope...
PPTX
Basics to java programming and concepts of java
PPTX
Detailed_description_on_java_ppt_final.pptx
PPTX
Inheritance & interface ppt Inheritance
PPTX
Java chapter 5
PPTX
Modules 333333333³3444444444444444444.pptx
PDF
Java programming -Object-Oriented Thinking- Inheritance
PPTX
Module 3 and 4-javahjhhdhdhddhhdhdhdhd.pptx
PPTX
Inheritance,single,multiple.access rulepptx
PPTX
Unit3 inheritance
PPTX
Inheritance Interface and Packags in java programming.pptx
PPTX
OBJECT ORIENTED PROGRAMMING_Unit2_firsthalf Updated.pptx
PPTX
Ch5 inheritance
PPTX
Inheritance in OOPs with java
OBJECT ORIENTED PROGRAMMING_Unit2_NOTES.pptx
‏‏‏‏‏‏oop lecture objectives will come.pdf
Java - Inheritance_multiple_inheritance.pptx
11.Object Oriented Programming.pdf
Java kkdhaksndjsjkanshdjdjdnsnxxhjdjdnxhxjx
java_inheritance_oop_20250730110153.pptx
Inheritance in Java is a mechanism in which one object acquires all the prope...
Basics to java programming and concepts of java
Detailed_description_on_java_ppt_final.pptx
Inheritance & interface ppt Inheritance
Java chapter 5
Modules 333333333³3444444444444444444.pptx
Java programming -Object-Oriented Thinking- Inheritance
Module 3 and 4-javahjhhdhdhddhhdhdhdhd.pptx
Inheritance,single,multiple.access rulepptx
Unit3 inheritance
Inheritance Interface and Packags in java programming.pptx
OBJECT ORIENTED PROGRAMMING_Unit2_firsthalf Updated.pptx
Ch5 inheritance
Inheritance in OOPs with java
Ad

More from DrYogeshDeshmukh1 (14)

PPTX
Unit No. 1 Introduction to Java.pptx
PPTX
Unit No 6 Design Patterns.pptx
PPTX
Unit No 5 Files and Database Connectivity.pptx
PPTX
Unit No 4 Exception Handling and Multithreading.pptx
PPTX
Unit No 2 Objects and Classes.pptx
PPTX
Unit 6 Uncertainty.pptx
PPTX
Unit 5 Introduction to Planning and ANN.pptx
PPTX
Unit 4 Knowledge Representation.pptx
PPTX
Unit 3 Informed Search Strategies.pptx
PPTX
DAA Unit 1 Part 1.pptx
PPTX
AI Overview.pptx
PPTX
Unit 2 Uninformed Search Strategies.pptx
PPTX
Unit 1 Fundamentals of Artificial Intelligence-Part II.pptx
PPTX
Unit 1 Fundamentals of Artificial Intelligence-Part I.pptx
Unit No. 1 Introduction to Java.pptx
Unit No 6 Design Patterns.pptx
Unit No 5 Files and Database Connectivity.pptx
Unit No 4 Exception Handling and Multithreading.pptx
Unit No 2 Objects and Classes.pptx
Unit 6 Uncertainty.pptx
Unit 5 Introduction to Planning and ANN.pptx
Unit 4 Knowledge Representation.pptx
Unit 3 Informed Search Strategies.pptx
DAA Unit 1 Part 1.pptx
AI Overview.pptx
Unit 2 Uninformed Search Strategies.pptx
Unit 1 Fundamentals of Artificial Intelligence-Part II.pptx
Unit 1 Fundamentals of Artificial Intelligence-Part I.pptx

Recently uploaded (20)

PPTX
Feature types and data preprocessing steps
PPTX
AUTOMOTIVE ENGINE MANAGEMENT (MECHATRONICS).pptx
PDF
Unit I -OPERATING SYSTEMS_SRM_KATTANKULATHUR.pptx.pdf
PDF
First part_B-Image Processing - 1 of 2).pdf
PDF
MLpara ingenieira CIVIL, meca Y AMBIENTAL
PDF
UEFA_Embodied_Carbon_Emissions_Football_Infrastructure.pdf
PPTX
wireless networks, mobile computing.pptx
PPTX
Graph Data Structures with Types, Traversals, Connectivity, and Real-Life App...
PDF
distributed database system" (DDBS) is often used to refer to both the distri...
PDF
Exploratory_Data_Analysis_Fundamentals.pdf
PPTX
A Brief Introduction to IoT- Smart Objects: The "Things" in IoT
PDF
null (2) bgfbg bfgb bfgb fbfg bfbgf b.pdf
PPT
Chapter 1 - Introduction to Manufacturing Technology_2.ppt
PDF
Implantable Drug Delivery System_NDDS_BPHARMACY__SEM VII_PCI .pdf
PPTX
Principal presentation for NAAC (1).pptx
PPTX
Software Engineering and software moduleing
PDF
UEFA_Carbon_Footprint_Calculator_Methology_2.0.pdf
PPTX
CyberSecurity Mobile and Wireless Devices
PDF
Design Guidelines and solutions for Plastics parts
PPTX
Management Information system : MIS-e-Business Systems.pptx
Feature types and data preprocessing steps
AUTOMOTIVE ENGINE MANAGEMENT (MECHATRONICS).pptx
Unit I -OPERATING SYSTEMS_SRM_KATTANKULATHUR.pptx.pdf
First part_B-Image Processing - 1 of 2).pdf
MLpara ingenieira CIVIL, meca Y AMBIENTAL
UEFA_Embodied_Carbon_Emissions_Football_Infrastructure.pdf
wireless networks, mobile computing.pptx
Graph Data Structures with Types, Traversals, Connectivity, and Real-Life App...
distributed database system" (DDBS) is often used to refer to both the distri...
Exploratory_Data_Analysis_Fundamentals.pdf
A Brief Introduction to IoT- Smart Objects: The "Things" in IoT
null (2) bgfbg bfgb bfgb fbfg bfbgf b.pdf
Chapter 1 - Introduction to Manufacturing Technology_2.ppt
Implantable Drug Delivery System_NDDS_BPHARMACY__SEM VII_PCI .pdf
Principal presentation for NAAC (1).pptx
Software Engineering and software moduleing
UEFA_Carbon_Footprint_Calculator_Methology_2.0.pdf
CyberSecurity Mobile and Wireless Devices
Design Guidelines and solutions for Plastics parts
Management Information system : MIS-e-Business Systems.pptx

Unit No 3 Inheritance annd Polymorphism.pptx

  • 1. Object Oriented Programming with Java Unit No. 2: Inheritance and Polymorphism Sanjivani Rural Education Society’s Sanjivani College of Engineering, Kopargaon-423603 (An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune) NAAC ‘A’ Grade Accredited, ISO 9001:2015 Certified Department of Information Technology (UG Course: NBA Accredited) Dr. Y.S.Deshmukh Assistant Professor
  • 2. Object Oriented Programming with Java Inheritance: 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. 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.
  • 3. Object Oriented Programming with Java Inheritance: 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. You can use the same fields and methods already defined in the previous class.
  • 4. Object Oriented Programming with Java Inheritance:
  • 5. Object Oriented Programming with Java Inheritance: 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); } }
  • 6. Object Oriented Programming with Java Types of inheritance in java
  • 7. Object Oriented Programming with Java Types of inheritance in java
  • 8. Object Oriented Programming with Java 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(); }}
  • 9. Object Oriented Programming with Java Multilevel Inheritance Example 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(); }}
  • 10. Object Oriented Programming with Java Hierarchical Inheritance Example 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 }}
  • 11. Object Oriented Programming with Java Why multiple inheritance is not supported in java? 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.
  • 12. Object Oriented Programming with Java Why multiple inheritance is not supported in java? 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? } }
  • 13. Object Oriented Programming with Java Polymorphism: Method Overloading in Java If a class has multiple methods having same name but different in parameters, it is known as Method Overloading. If we have to perform only one operation, having same name of the methods increases the readability of the program. Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it may be difficult for you as well as other programmers to understand the behavior of the method because its name differs.
  • 14. Object Oriented Programming with Java Polymorphism: Method Overloading in Java Advantage of method overloading Method overloading increases the readability of the program. Different ways to overload the method There are two ways to overload the method in java • By changing number of arguments • By changing the data type 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;} } class TestOverloading1{ public static void main(String[] args){ System.out.println(Adder.add(11,11)); System.out.println(Adder.add(11,11,11)); }}
  • 15. Object Oriented Programming with Java Polymorphism: Method Overloading in Java class Adder{ static int add(int a, int b){return a+b;} static double add(double a, double b){return a+b;} } class TestOverloading2{ public static void main(String[] args){ System.out.println(Adder.add(11,11)); System.out.println(Adder.add(12.3,12.6)); }}
  • 16. Object Oriented Programming with Java Polymorphism: Method Overriding in Java If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Java. In other words, If a subclass provides the specific implementation of the method that has been declared by one of its parent class, it is known as method overriding. Usage of Java Method Overriding • Method overriding is used to provide the specific implementation of a method which is already provided by its superclass. • Method overriding is used for runtime polymorphism
  • 17. Object Oriented Programming with Java Polymorphism: Method Overriding in Java Rules for Java Method Overriding • The method must have the same name as in the parent class • The method must have the same parameter as in the parent class. • There must be an IS-A relationship (inheritance). class Vehicle{ void run(){System.out.println("Vehicle is running");} } //Creating a child class class Bike extends Vehicle{ public static void main(String args[]){ //creating an instance of child class Bike obj = new Bike(); //calling the method with child class instance obj.run(); } }
  • 18. Object Oriented Programming with Java Super Keyword in Java The super keyword in Java is a reference variable which is used to refer immediate parent class object. Whenever you create the instance of subclass, an instance of parent class is created implicitly which is referred by super reference variable. Usage of Java super Keyword • super can be used to refer immediate parent class instance variable. • super can be used to invoke immediate parent class method. • super() can be used to invoke immediate parent class constructor.
  • 19. Object Oriented Programming with Java Super Keyword in Java
  • 20. Object Oriented Programming with Java 1.class Animal{ 2.String color="white"; 3.} 4.class Dog extends Animal{ 5.String color="black"; 6.void printColor(){ 7.System.out.println(color);//prints color of Dog class 8.System.out.println(super.color);//prints color of Animal cl ass 9.} 10.} 11.class TestSuper1{ 12.public static void main(String args[]){ 13.Dog d=new Dog(); 14.d.printColor(); 15.}}
  • 21. Object Oriented Programming with Java class Animal{ void eat(){System.out.println("eating...");} } class Dog extends Animal{ void eat(){System.out.println("eating bread...");} void bark(){System.out.println("barking...");} void work(){ super.eat(); bark(); } } class TestSuper2{ public static void main(String args[]){ Dog d=new Dog(); d.work(); }}
  • 22. Object Oriented Programming with Java class Animal{ Animal(){System.out.println("animal is created");} } class Dog extends Animal{ Dog(){ super(); System.out.println("dog is created"); } } class TestSuper3{ public static void main(String args[]){ Dog d=new Dog(); }}
  • 23. Object Oriented Programming with Java Abstract Classes A class which is declared with the abstract keyword is known as an abstract class in Java. It can have abstract and non-abstract methods (method with the body). Abstraction in Java: Abstraction is a process of hiding the implementation details and showing only functionality to the user. Another way, it shows only essential things to the user and hides the internal details, for example, sending SMS where you type the text and send the message. You don't know the internal processing about the message delivery. Ways to achieve Abstraction: There are two ways to achieve abstraction in java Abstract class (0 to 100%) Interface (100%)
  • 24. Object Oriented Programming with Java Abstract Classes Abstract class in Java A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract methods. It needs to be extended and its method implemented. It cannot be instantiated. • An abstract class must be declared with an abstract keyword. • It can have abstract and non-abstract methods. • It cannot be instantiated. • It can have constructors and static methods also. • It can have final methods which will force the subclass not to change the body of the method.
  • 25. Object Oriented Programming with Java Abstract Classes
  • 26. Object Oriented Programming with Java Abstract Methods A method which is declared as abstract and does not have implementation is known as an abstract method. abstract void printStatus(); abstract class A{} abstract class Bike{ abstract void run(); } class Honda4 extends Bike{ void run(){System.out.println("running safely");} public static void main(String args[]){ Bike obj = new Honda4(); obj.run(); } }
  • 27. Object Oriented Programming with Java Abstract Classes & Methods: Abstract class having constructor, data member and methods An abstract class can have a data member, abstract method, method body (non-abstract method), constructor, and even main() method. abstract class Bike{ Bike(){System.out.println("bike is created");} abstract void run(); void changeGear(){System.out.println("gear changed");} } class Honda extends Bike{ void run(){System.out.println("running safely..");} } class TestAbstraction2{ public static void main(String args[]){ Bike obj = new Honda(); obj.run(); obj.changeGear();
  • 28. Object Oriented Programming with Java Interface in Java: An interface in Java is a blueprint of a class. It has static constants and abstract methods. The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance in Java. In other words, you can say that interfaces can have abstract methods and variables. It cannot have a method body. Java Interface also represents the IS-A relationship. It cannot be instantiated just like the abstract class. Since Java 8, we can have default and static methods in an interface. Since Java 9, we can have private methods in an interface.
  • 29. Object Oriented Programming with Java Interface in Java: Why use Java interface? It is used to achieve abstraction. By interface, we can support the functionality of multiple inheritance. It can be used to achieve loose coupling.
  • 30. Object Oriented Programming with Java Interface in Java: Syntax: interface <interface_name>{ // declare constant fields // declare methods that abstract // by default. }
  • 31. Object Oriented Programming with Java Interface in Java: The relationship between classes and interfaces As shown in the figure given below, a class extends another class, an interface extends another interface, but a class implements an interface.
  • 32. Object Oriented Programming with Java Interface in Java: interface Bank{ float rateOfInterest(); } class SBI implements Bank{ public float rateOfInterest(){return 9.15f;} } class PNB implements Bank{ public float rateOfInterest(){return 9.7f;} } class TestInterface2{ public static void main(String[] args){ Bank b=new SBI(); System.out.println("ROI: "+b.rateOfInterest()); }}
  • 33. Object Oriented Programming with Java Interface in Java: Multiple inheritance in Java by interface If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as multiple inheritance.
  • 34. Object Oriented Programming with Java Interface in Java: interface Printable{ void print(); } interface Showable{ void show(); } class A7 implements Printable,Showable{ public void print(){System.out.println("Hello");} public void show(){System.out.println("Welcome");} public static void main(String args[]){ A7 obj = new A7(); obj.print(); obj.show(); } }
  • 35. Object Oriented Programming with Java Interface in Java: Multiple inheritance is not supported through class in java, but it is possible by an interface, why? As we have explained in the inheritance chapter, multiple inheritance is not supported in the case of class because of ambiguity. However, it is supported in case of an interface because there is no ambiguity. It is because its implementation is provided by the implementation class. For example: interface Printable{ void print(); } interface Showable{ void print(); } class TestInterface3 implements Printable, Showable{ public void print(){System.out.println("Hello");} public static void main(String args[]){ TestInterface3 obj = new TestInterface3(); obj.print(); } }
  • 36. Object Oriented Programming with Java Java Package: A java package is a group of similar types of classes, interfaces and sub-packages. Package in java can be categorized in two form, built-in package and user-defined package. There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc. Here, we will have the detailed learning of creating and using user-defined packages. Advantage of Java Package 1) Java package is used to categorize the classes and interfaces so that they can be easily maintained. 2) Java package provides access protection. 3) Java package removes naming collision.
  • 37. Object Oriented Programming with Java Java Package:
  • 38. Object Oriented Programming with Java Java Package: Simple example of java package The package keyword is used to create a package in java. //save as Simple.java package mypack; public class Simple{ public static void main(String args[]){ System.out.println("Welcome to package"); } } How to compile java package If you are not using any IDE, you need to follow the syntax given below: javac -d directory javafilename javac -d . Simple.java
  • 39. Object Oriented Programming with Java Java Package: The -d switch specifies the destination where to put the generated class file. You can use any directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to keep the package within the same directory, you can use . (dot). How to run java package program You need to use fully qualified name e.g. mypack.Simple etc to run the class. To Compile: javac -d . Simple.java To Run: java mypack.Simple The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The . represents the current folder.
  • 40. Object Oriented Programming with Java Java Package: How to access package from another package? There are three ways to access the package from outside the package. • import package.*; • import package.classname; • fully qualified name. 1) Using packagename.* If you use package.* then all the classes and interfaces of this package will be accessible but not subpackages. The import keyword is used to make the classes and interface of another package accessible to the current package.
  • 41. Object Oriented Programming with Java Java Package: Example of package that import the packagename.* //save by A.java package pack; public class A{ public void msg(){System.out.println("Hello");} } //save by B.java package mypack; import pack.*; class B{ public static void main(String args[]){ A obj = new A(); obj.msg(); } }
  • 42. Object Oriented Programming with Java Java Package: 2) Using packagename.classname //save by A.java package pack; public class A{ public void msg(){System.out.println("Hello");} } //save by B.java package mypack; import pack.A; class B{ public static void main(String args[]){ A obj = new A(); obj.msg(); } }
  • 43. Object Oriented Programming with Java Java Package: 3) Using fully qualified name //save by A.java package pack; public class A{ public void msg(){System.out.println("Hello");} } //save by B.java package mypack; class B{ public static void main(String args[]){ pack.A obj = new pack.A();//using fully qualified name obj.msg(); } }
  • 44. Object Oriented Programming with Java Thank You