SlideShare a Scribd company logo
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).
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.
The syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
Inheritance in java computer programming app
Single Inheritance Example
TestInheritance.java
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();
}}
Output:
barking... eating.
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();
}}
Output:
• weeping... barking... eating...
Hierarchical Inheritance
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
}}
Output:
meowing... eating..
#include <iostream>
using namespace std;
// Base class 1
class Base1
{
public:
void show() {
cout << "Base1::show()" << endl;
}
};
// Base class 2
class Base2
{
public:
void display()
{ cout << "Base2::display()" << endl;
}};
// Derived class
class Derived : public Base1, public Base2
{
};
int main()
{
Derived d;
d.show(); // Access method from Base1
d.display(); // Access method from Base2
return 0;
}
// Class 3
// Trying to be child of both the classes
class Test extends Parent1,Parent2 {
// Main driver method
public static void main(String args[]) {
// Creating object of class in main() method
Test t = new Test();
// Trying to call above functions of class
where
// Error is thrown as this class is inheriting
// multiple classes
t.fun();
}
}
import java.io.*;
class Parent1 {
void fun() {
System.out.println("Parent1");
}
}
class Parent2 {
void fun() {
// Print statement if this method is called
System.out.println("Parent2");
}
}
Java doesn’t support Multiple Inheritance
Java Polymorphism
1. Method Overloading
2. Method Overriding
• If a class has multiple methods having same name but different in
parameters, it is known as Method Overloading.
There are two ways to overload the method in java
• By changing number of arguments
• By changing the data type
Method Overloading: changing no. 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;}
}
class TestOverloading1
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}
}
Output:
• 22
• 33
Method Overloading: changing data type of arguments
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));
}}
Output:
22 24.9
Method Overriding
If subclass (child class) has the same method as declared in the parent
class, it is known as method overriding .
Usage of 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.
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
{
//defining a method
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike2 extends Vehicle
{
//defining the same method as in the parent class
void run(){System.out.println("Bike is running safely");
}
public static void main(String args[])
{
Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}
Output:
Bike is running safely
class Bank{
int getRateOfInterest(){return 0;}
}
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}
class ICICI extends Bank{
int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
class Test2{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}
• Output: SBI Rate of Interest: 8 ICICI Rate of Interest: 7 AXIS Rate of Interest: 9
Encapsulation in Java
• Encapsulation in Java is a process of wrapping code and data
together into a single unit, for example, a capsule which is mixed of
several medicines.
• We can create a fully encapsulated class in Java by making all the data
members of the class private. Now we can use setter and getter
methods to set and get the data in it.
• The Java Bean class is the example of a fully encapsulated class.
Advantage of Encapsulation:
• By providing only a setter or getter method, you can make the class read-only or
write-only.
• It provides you the control over the data. Suppose you want to set the value of id
which should be greater than 100 only, you can write the logic inside the setter
method. You can write the logic not to store the negative numbers in the setter
methods.
• It is a way to achieve data hiding in Java because other class will not be able to
access the data through the private data members.
• The encapsulate class is easy to test. So, it is better for unit testing.
• The standard IDE's (integrated development environment) are providing the facility
to generate the getters and setters. So, it is easy and fast to create an encapsulated
class in Java.
// set method for age to access
// private variable geekage
public void setAge(int newAge)
{ geekAge = newAge; }
// set method for name to access
// private variable geekName
public void setName(String newName)
{
geekName = newName;
}
// set method for roll to access
// private variable geekRoll
public void setRoll(int newRoll)
{ geekRoll = newRoll; }
}
class Encapsulate {
// private variables declared
// these can only be accessed by
// public methods of class
private String geekName;
private int geekRoll;
private int geekAge;
// get method for age to access
// private variable geekAge
public int getAge() { return geekAge; }
// get method for name to access
// private variable geekName
public String getName() { return geekName; }
// get method for roll to access
// private variable geekRoll
public int getRoll() { return geekRoll; }
// Class to access variables
// of the class Encapsulate
public class Test {
public static void main(String[]
args)
{
Encapsulate obj = new
Encapsulate();
// setting values of the variables
obj.setName("Harsh");
obj.setAge(19);
obj.setRoll(51);
// Displaying values of the variables
System.out.println("Geek's name: " +
obj.getName());
System.out.println("Geek's age: " +
obj.getAge());
System.out.println("Geek's roll: " +
obj.getRoll());
// Direct access of geekRoll is not possible
// due to encapsulation
// System.out.println(&quot;Geek's roll:
&quot; +
// obj.geekName);
}
}
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.
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.
Inheritance in java computer programming app
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
Create the folder mypack
Inside mypack save the program file: File name is Simple
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.
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.
import package.*;
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
import package.classname;
package pkg;
public class AA
{
public void msg()
{ System.out.println("Hello")
;
}
}
import pkg.AA;
class BB{
public static void main(String args[]){
AA obj = new AA();
obj.msg();
}
}
fully qualified name
package pkg1;
public class AAA
{
public void msg()
{
System.out.println("Hello");
}
}
import pkg1.*;
class BBB{
public static void main(String args[]){
pkg1.AAA obj = new pkg1.AAA();//using
fully qualified name
obj.msg();
}
}
PACKAGE 1:
package student;
public class stud
{
int regno;
String name;
public stud(int r,String n)
{
regno=r;
name=n;
}
public void print()
{
System.out.println("Regino="+regno);
System.out.println("Name="+name);
}
}
package diploma;
public class diplo
{
int regno;
String disp;
String year;
public diplo(String d,String y)
{
disp=d;
year=y;
}
public void print()
{
System.out.println("course="+disp);
System.out.println("year="+year);
}
}
PACKAGE 2:
IMPORT PACKAGE
import student.stud;
import diploma.diplo;
class clg
{
public static void main(String args[])
{
stud s=new stud(111,"Anandh");
diplo d=new diplo(“CSE","IIId year");
s.print();
d.print();
}
}

More Related Content

PPTX
Modules 333333333³3444444444444444444.pptx
PPTX
Basics to java programming and concepts of java
PPTX
Detailed_description_on_java_ppt_final.pptx
PPTX
PPTX
inheritance.pptx
PPT
Corejava Training in Bangalore Tutorial
PPTX
702641313-CS3391-OBJORIENTEDPS-Unit-2.pptx
PDF
Access modifiers
Modules 333333333³3444444444444444444.pptx
Basics to java programming and concepts of java
Detailed_description_on_java_ppt_final.pptx
inheritance.pptx
Corejava Training in Bangalore Tutorial
702641313-CS3391-OBJORIENTEDPS-Unit-2.pptx
Access modifiers

Similar to Inheritance in java computer programming app (20)

PDF
Object Oriented Programming using JAVA Notes
PPTX
inheritance
PPTX
UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
PPTX
Unit3 inheritance
PPTX
Java assignment help
PPTX
Inheritance & interface ppt Inheritance
PPTX
Introduction of Object Oriented Programming Language using Java. .pptx
PPTX
THE PACKAGES CONCEPT IN JAVA PROGRAMMING.pptx
PPTX
Object Oriented Programming Inheritance with case study
PDF
Top 50 Java Interviews Questions | Tutort Academy - Course for Working Profes...
PPTX
UNIT 3- Java- Inheritance, Multithreading.pptx
PPTX
UNIT - IIInew.pptx
PPTX
Advance example of Classes and object and programming with case study
PPT
Best Core Java Training In Bangalore
PDF
Java Reflection
PPT
web program-Inheritance,pack&except in Java.ppt
PPTX
Introduction to java programming
PPTX
object oriented programming using java, second sem BCA,UoM
PPTX
Unit3 part2-inheritance
PPTX
Chap-3 Inheritance.pptx
Object Oriented Programming using JAVA Notes
inheritance
UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
Unit3 inheritance
Java assignment help
Inheritance & interface ppt Inheritance
Introduction of Object Oriented Programming Language using Java. .pptx
THE PACKAGES CONCEPT IN JAVA PROGRAMMING.pptx
Object Oriented Programming Inheritance with case study
Top 50 Java Interviews Questions | Tutort Academy - Course for Working Profes...
UNIT 3- Java- Inheritance, Multithreading.pptx
UNIT - IIInew.pptx
Advance example of Classes and object and programming with case study
Best Core Java Training In Bangalore
Java Reflection
web program-Inheritance,pack&except in Java.ppt
Introduction to java programming
object oriented programming using java, second sem BCA,UoM
Unit3 part2-inheritance
Chap-3 Inheritance.pptx
Ad

Recently uploaded (20)

PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PPTX
bas. eng. economics group 4 presentation 1.pptx
DOCX
573137875-Attendance-Management-System-original
PPTX
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
PDF
Well-logging-methods_new................
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PPTX
Internet of Things (IOT) - A guide to understanding
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PPT
Mechanical Engineering MATERIALS Selection
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PPTX
UNIT 4 Total Quality Management .pptx
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PDF
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
PPTX
Welding lecture in detail for understanding
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
bas. eng. economics group 4 presentation 1.pptx
573137875-Attendance-Management-System-original
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
Well-logging-methods_new................
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
Internet of Things (IOT) - A guide to understanding
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
Mechanical Engineering MATERIALS Selection
Embodied AI: Ushering in the Next Era of Intelligent Systems
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
UNIT 4 Total Quality Management .pptx
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
Welding lecture in detail for understanding
Ad

Inheritance in java computer programming app

  • 2. • 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). 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. The syntax of Java Inheritance class Subclass-name extends Superclass-name { //methods and fields }
  • 4. Single Inheritance Example TestInheritance.java 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(); }} Output: barking... eating.
  • 5. 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(); }} Output: • weeping... barking... eating...
  • 6. Hierarchical Inheritance 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 }} Output: meowing... eating..
  • 7. #include <iostream> using namespace std; // Base class 1 class Base1 { public: void show() { cout << "Base1::show()" << endl; } }; // Base class 2 class Base2 { public: void display() { cout << "Base2::display()" << endl; }}; // Derived class class Derived : public Base1, public Base2 { }; int main() { Derived d; d.show(); // Access method from Base1 d.display(); // Access method from Base2 return 0; }
  • 8. // Class 3 // Trying to be child of both the classes class Test extends Parent1,Parent2 { // Main driver method public static void main(String args[]) { // Creating object of class in main() method Test t = new Test(); // Trying to call above functions of class where // Error is thrown as this class is inheriting // multiple classes t.fun(); } } import java.io.*; class Parent1 { void fun() { System.out.println("Parent1"); } } class Parent2 { void fun() { // Print statement if this method is called System.out.println("Parent2"); } } Java doesn’t support Multiple Inheritance
  • 9. Java Polymorphism 1. Method Overloading 2. Method Overriding • If a class has multiple methods having same name but different in parameters, it is known as Method Overloading. There are two ways to overload the method in java • By changing number of arguments • By changing the data type
  • 10. Method Overloading: changing no. 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;} } class TestOverloading1 { public static void main(String[] args) { System.out.println(Adder.add(11,11)); System.out.println(Adder.add(11,11,11)); } } Output: • 22 • 33
  • 11. Method Overloading: changing data type of arguments 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)); }} Output: 22 24.9
  • 12. Method Overriding If subclass (child class) has the same method as declared in the parent class, it is known as method overriding . Usage of 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. 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).
  • 13. class Vehicle { //defining a method void run(){System.out.println("Vehicle is running");} } //Creating a child class class Bike2 extends Vehicle { //defining the same method as in the parent class void run(){System.out.println("Bike is running safely"); } public static void main(String args[]) { Bike2 obj = new Bike2();//creating object obj.run();//calling method } } Output: Bike is running safely
  • 14. class Bank{ int getRateOfInterest(){return 0;} } class SBI extends Bank{ int getRateOfInterest(){return 8;} } class ICICI extends Bank{ int getRateOfInterest(){return 7;} } class AXIS extends Bank{ int getRateOfInterest(){return 9;} } class Test2{ public static void main(String args[]){ SBI s=new SBI(); ICICI i=new ICICI(); AXIS a=new AXIS(); System.out.println("SBI Rate of Interest: "+s.getRateOfInterest()); System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest()); System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest()); } } • Output: SBI Rate of Interest: 8 ICICI Rate of Interest: 7 AXIS Rate of Interest: 9
  • 15. Encapsulation in Java • Encapsulation in Java is a process of wrapping code and data together into a single unit, for example, a capsule which is mixed of several medicines. • We can create a fully encapsulated class in Java by making all the data members of the class private. Now we can use setter and getter methods to set and get the data in it. • The Java Bean class is the example of a fully encapsulated class.
  • 16. Advantage of Encapsulation: • By providing only a setter or getter method, you can make the class read-only or write-only. • It provides you the control over the data. Suppose you want to set the value of id which should be greater than 100 only, you can write the logic inside the setter method. You can write the logic not to store the negative numbers in the setter methods. • It is a way to achieve data hiding in Java because other class will not be able to access the data through the private data members. • The encapsulate class is easy to test. So, it is better for unit testing. • The standard IDE's (integrated development environment) are providing the facility to generate the getters and setters. So, it is easy and fast to create an encapsulated class in Java.
  • 17. // set method for age to access // private variable geekage public void setAge(int newAge) { geekAge = newAge; } // set method for name to access // private variable geekName public void setName(String newName) { geekName = newName; } // set method for roll to access // private variable geekRoll public void setRoll(int newRoll) { geekRoll = newRoll; } } class Encapsulate { // private variables declared // these can only be accessed by // public methods of class private String geekName; private int geekRoll; private int geekAge; // get method for age to access // private variable geekAge public int getAge() { return geekAge; } // get method for name to access // private variable geekName public String getName() { return geekName; } // get method for roll to access // private variable geekRoll public int getRoll() { return geekRoll; }
  • 18. // Class to access variables // of the class Encapsulate public class Test { public static void main(String[] args) { Encapsulate obj = new Encapsulate(); // setting values of the variables obj.setName("Harsh"); obj.setAge(19); obj.setRoll(51); // Displaying values of the variables System.out.println("Geek's name: " + obj.getName()); System.out.println("Geek's age: " + obj.getAge()); System.out.println("Geek's roll: " + obj.getRoll()); // Direct access of geekRoll is not possible // due to encapsulation // System.out.println(&quot;Geek's roll: &quot; + // obj.geekName); } }
  • 19. 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. 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.
  • 21. //save as Simple.java package mypack; public class Simple{ public static void main(String args[]){ System.out.println("Welcome to package"); } } Create the folder mypack Inside mypack save the program file: File name is Simple
  • 22. 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. 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.
  • 23. import package.*; package pack; public class A { public void msg() { System.out.println("Hello"); } } import pack.*; class B { public static void main(String args[]) { A obj = new A(); obj.msg(); } }
  • 24. import package.classname; package pkg; public class AA { public void msg() { System.out.println("Hello") ; } } import pkg.AA; class BB{ public static void main(String args[]){ AA obj = new AA(); obj.msg(); } }
  • 25. fully qualified name package pkg1; public class AAA { public void msg() { System.out.println("Hello"); } } import pkg1.*; class BBB{ public static void main(String args[]){ pkg1.AAA obj = new pkg1.AAA();//using fully qualified name obj.msg(); } }
  • 26. PACKAGE 1: package student; public class stud { int regno; String name; public stud(int r,String n) { regno=r; name=n; } public void print() { System.out.println("Regino="+regno); System.out.println("Name="+name); } } package diploma; public class diplo { int regno; String disp; String year; public diplo(String d,String y) { disp=d; year=y; } public void print() { System.out.println("course="+disp); System.out.println("year="+year); } } PACKAGE 2:
  • 27. IMPORT PACKAGE import student.stud; import diploma.diplo; class clg { public static void main(String args[]) { stud s=new stud(111,"Anandh"); diplo d=new diplo(“CSE","IIId year"); s.print(); d.print(); } }