SlideShare a Scribd company logo
UNIT-2
INHERITANCE AND
INTERFACES
UNIT II
INHERITANCE AND INTERFACES
Inheritance – Super classes- sub classes –Protected members –
constructors in sub classes- the Object class – abstract classes
and methods- final methods and classes – Interfaces – defining
an interface, implementing interface, differences between classes
and interfaces and extending interfaces - Object cloning -inner
classes, ArrayLists - Strings
INHERITANCE
 When one object acquires all the properties and
behaviors of a parent object, it is known as
inheritance.
 It provides code reusability. It is used to achieve
runtime polymorphism.
USES OF INHERITANCE IN
JAV
A
o For Method Overriding.
o For Code Reusability.
 Syntax:
class subClass extends superClass
{
//methods and fields
}
Method overloading:
Void add(int a, int b)
Void add(int a, int b, int c)
Void add(float a,float b)
Method Overriding:
Void add(int a, int b)
Void add(int a, int b)
TYPES OF INHERITANCE
 Single Inheritance
 Multilevel Inheritance
 Hierarchical inheritance.
 Multiple & Hybrid inheritance is supported
through interface only.
OOPS_Unit2.inheritance and interface objected oriented programming
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
properties of 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 previous class.
SINGLE INHERITANCE
 When a class inherits another class, it is known
as a single inheritance.
OOPS_Unit2.inheritance and interface objected oriented programming
MULTI LEVEL INHERITANCE
Class B,A
Class C,B,A
OOPS_Unit2.inheritance and interface objected oriented programming
HIERARCHICAL INHERITANCE
HIERARCHICAL INHERITANCE
class Animal
{
void eat(){
System.out.println("Anim
als are eating");
} }
class Dog extends Animal{
void eat1(){
System.out.println("Dog is
eating");
} }
class Cat extends Animal{
void eat2(){
System.out.println("Cat is
eating");
} }
class Deer extends
Animal{
void eat3(){
System.out.println(
"Deer
is eating");
} }
class Hi{
public static void
main(String args[])
{
Deer d1=new Deer();
d1.eat();
Cat c1=new Cat();
c1.eat2();
Dog d=new Dog();
d.eat1();
d1.eat3();
OOPS_Unit2.inheritance and interface objected oriented programming
 Multiple Inheritance and Hybrid Inheritance will be
handled
with the concept of interface.
SUPER KEYWORD
 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.
USES OF SUPER
KEYWORD
Usage of super keyword
1. super() invokes the constructor of the parent class.
2. super.variable_name refers to the variable in the
parent class.
3. super.method_name refers to the method of the parent
class
EXAMPL
E
class Animal
{ void eat(){
System.out.pri
ntln("Animals
are eating");
} }
class Dog extends
Animal{ void eat(){
System.out.println("Dog is
eating");
super.eat();// here super
keyword refers to the
immediate parent class
}
class Super1{
public static void
main(String args[]){
OOPS_Unit2.inheritance and interface objected oriented programming
1) SUPER IS USED TO REFER IMMEDIATE
PARENT CLASS INSTANCE VARIABLE.
class Animal{
String color="white";
}
class Dog extends
Animal{ String color="black";
void printColor(){
System.out.println(color);//
prints color of Dog class
System.out.println(super.colo
r);//prints color of Animal
class
}
}
class TestSuper1{
public static void
main(String args[]){
Dog d=new Dog();
OOPS_Unit2.inheritance and interface objected oriented programming
2) SUPER CAN BE USED TO INVOKE PARENT
CLASS METHOD
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();
}}
OOPS_Unit2.inheritance and interface objected oriented programming
3) SUPER IS USED TO INVOKE PARENT
CLASS CONSTRUCTOR.
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();
}}
class Person{
int id;
String name;
Person(int
id,String
name){
this.id=id;
this.name=name;
} }
class Emp
extends Person{
float salary;
Emp(int id,String name,float salary)
{ super(id,name);//reusing parent constructor
this.salary=salary;
}
void display(){System.out.println(id+"
"+name+" "+salary);}
}
class TestSuper5{
public static void main(String[] args)
PROTECTED MEMBERS
 Protected data member and method are only
accessible by the classes of the same package and
the subclasses present in any package.
 You can also say that the protected access
modifier is similar to default access modifier with
one exception that it has visibility in sub classes.
 Classes cannot be declared protected.
 This access modifier is generally used in a parent
child relationship.
EXAMPL
E
Addition.java package
abcpackage; public
class Addition {
protected int
addTwoNumbers(int a,
int b)
{ return a+b; } }
Test.java
package xyzpackage;
import abcpackage.*;
class Test extends
Addition{
public static void main(String args[])
{ Test obj = new Test();
THE OBJECT
CLASS
 There is one special class called Object, defined by Java.
 All other classes are subclasses of Object.
 That is, Object is a super class of all other classes.
 This means that a reference variable of type Object can refer to an object of
any other class.
 Object defines the following methods, which means that they are available
in every object.
OOPS_Unit2.inheritance and interface objected oriented programming
ABSTRACT CLASS
 A class that is declared with abstract keyword, is
known as abstract class in java.
 The method which is defined inside the abstract class
can be abstract method or non abstract method.
OOPS_Unit2.inheritance and interface objected oriented programming
ABSTRACT METHOD
 The abstract class can also be used to provide
some implementation of the interface.
 In such case, the end user may not be forced to override
all the methods of the interface.
EXAMPLE
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.
USES OF INTERFACE
DECLARATION OF INTERFACE
 An interface is declared by using the interface
keyword.
 It provides total abstraction- means all the
methods in an interface are declared with the
empty body, and all the fields are public, static
and final by default.
 A class that implements an interface must
implement all the methods declared in the
interface.
SYNTAX
interface <interface_name>{
/
/ declare constant fields
/
/ declare methods that abstract
/
/ by default.
}
COMPILER POINT OF VIEW
ABOUT INTERFACE
EXAMPLE
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
public static void main(String args[])
{ A6 obj = new A6();
obj.print();
}
}
interface Drawable{
void draw();
}
//Implementation: by second user
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class Circle implements Drawable{
public void draw(){System.out.println("drawing circle");}
}
//Using interface: by third user
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();//In real scenario, object is provided
by method e.g. getDrawable()
d.draw();
}}
OOPS_Unit2.inheritance and interface objected oriented programming
OOPS_Unit2.inheritance and interface objected oriented programming
 Multiple inheritance in Java by interface .
 If a class implements multiple interfaces, or an interface
extends
multiple interfaces i.e. known as multiple inheritance.
MULTIPLE INHERITANCE
EXAMPLE
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();
} }
EXAMPLE
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{ public
void print(){System.out.println("Hello");} public void
show(){System.out.println("Welcome");}
public static void main(String args[])
{ TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
} }
HYBRID INHERITANCE
 Hybrid Inheritance is a combination of
both SingleInheritance and Multiple
Inheritance.
 Since in Java Multiple Inheritance
supported directly we can achieve
inheritance also through Interfaces only.
is
not
Hybrid
HYBRID INHERITANCE
EXAMPLE
public class ClassA
{ public void dispA() {
System.out.println("disp() method of ClassA"); } }
public interface InterfaceB {
public void show(); }
public interface InterfaceC
{ public void show(); }
public class ClassD extends ClassA implements
InterfaceB,InterfaceC { public void show()
{ System.out.println("show() method
implementation"); }
EXAMPLE
public void dispD() { System.out.println("disp()
method of ClassD");
}
public static void main(String args[])
{ ClassD d = new ClassD();
d.dispD();
d.show(); } }
FINAL KEYWORD
Final keyword can be used along with variables, methods and
classes.
1) Final variable
 A final variable is a variable whose value cannot be changed
at anytime once assigned, it remains as a constant forever.
2) Final method
 When you declare a method as final, then it is called as final
method. A final method cannot be overridden.
3) Final class
 A final class cannot be extended(cannot be subclassed)
Java final variable
Java final method
Java final class
OOPS_Unit2.inheritance and interface objected oriented programming
OBJECT CLONING
 The object cloning is a way to create exact copy of an object.
 The clone() method of Object class is used to clone an object.
 The java.lang.Cloneable interface must be implemented by the class
whose object clone we want to create.
 If we don't implement Cloneable interface, clone() method generates
CloneNotSupportedException.
 The clone() method is defined in the Object class.
Syntax of the clone() method:
 protected Object clone() throws CloneNotSupportedException
OOPS_Unit2.inheritance and interface objected oriented programming
INNER CLASSES
 Java inner class or nested class is a class which is
declared
inside the class or interface.
 We use inner classes to logically group classes and interfaces in
one place so that it can be more readable and maintainable.
 Additionally, it can access all the members of outer
class
including private data members and methods.
Syntax of Inner
class
class Java_Outer_class{
//code
class Java_Inner_class{
//code
}
}
ADVANTAGE OF JAVA INNER
CLASSES
 There are basically three advantages of inner
classes in java. They are as follows:
⚫ Nested classes represent a special type
of relationship that is it can access all the
members (data members and methods)
of outer class including private.
⚫ Nested classes are used to develop more readable
and maintainable code because it logically group
classes and interfaces in one place only.
⚫ Code Optimization: It requires less code to write.
TYPES OF NESTED CLASSES
 There are two types of nested classes non-static
and static nested classes.
 The non-static nested classes are also known as
inner classes.
1) Non-static nested class (inner class)
 Member inner class
 Anonymous inner class
 Local inner class
2) Static nested class
TYPES OF NESTED CLASSES
Type Description
Member Inner Class A class created within class
and outside method.
Anonymous Inner Class A class created for implementing
interface or extending class. Its
name is decided by the java
compiler.
Local Inner Class A class created within method.
Static Nested Class A static class created within class.
Nested Interface An interface created within class or
interface.
1. JAVA MEMBER INNER CLASS
class
TestMemberOuter1{ privat
e int data=30; class
Inner{
void msg()
{System.out.println("data
is "+data);}
}
public static void main(String args[])
{ TestMemberOuter1 obj=new TestMemberOuter1(
);
TestMemberOuter1.Inner in=obj.new Inner();
in.msg();
2. ANONYMOUS INNER CLASS
 A class that have no name is known
as anonymous inner class in java.
 It should be used if you have to override method
of class or interface.
 Java Anonymous inner class can be created
by
two ways:
1. Class (may be abstract or concrete).
2. Interface
2.1 JAVA ANONYMOUS INNER
CLASS EXAMPLE USING
CLASS
abstract class Person{
abstract void eat();
}
class TestAnonymousInner{
public static void main(String args[])
{ Person p=new Person(){
void eat(){System.out.println("nice
fruits");}
};
p.eat();
}
}
2.2 JAVA ANONYMOUS INNER
CLASS EXAMPLE USING
INTERFACE
interface Eatable{
void eat();
}
class TestAnno{
public static void main(String args[])
{ Eatable e=new Eatable(){
public void eat()
{System.out.println("nice fruits"
);}
};
e.eat();
}
}
3. LOCAL INNER CLASS
 A class i.e. created inside a method is called local
inner class in java.
 If you want to invoke the methods of local inner
class, you must instantiate this class inside the
method.
JAVA LOCAL INNER CLASS
EXAMPLE
public class localInner1{
private int data=30;//instance variable
void display(){
class Local{
void msg(){System.out.println(data);}
}
Local l=new Local();
l.msg();
}
public static void
main(String args[]){
localInner1 obj=new
localInner1();
obj.display();
}
EXAMPLE OF LOCAL INNER CLASS
WITH LOCAL VARIABLE
class localInner2{
private int data=30;//instance variable
void display(){
int value=50;//local variable must be final till jdk 1.7 only
class Local{
void msg(){System.out.println(value);}
}
Local l=new Local();
l.msg();
}
public static void
main(String args[]){
localInner2 obj=new
localInner2();
obj.display();
}
4. JAVA STATIC NESTED CLASS
 A static class i.e. created inside a class is called
static nested class in java.
 It cannot access non-static data members
and methods.
 It can be accessed by outer class name.
 It can access static data members of outer
class including private.
 Static nested class cannot access non-
static (instance) data member or method.
JAVA STATIC NESTED CLASS EXAMPLE
WITH INSTANCE METHOD
class
TestOuter1{ static
int data=30; static
class Inner{
void msg()
{System.out.println
("data is "+data);}
}
public static void main(String args[])
{ TestOuter1.Inner obj=new TestOuter1.Inner();
obj.msg();
}
JAVA ARRAYLIST
CLASS
 Java ArrayList class uses a dynamic array for storing the elements.
 It inherits AbstractList class and implements List interface.
 The important points about Java ArrayList class are:
⚫ Java ArrayList class can contain duplicate elements.
⚫ Java ArrayList class maintains insertion order.
⚫ Java ArrayList class is non synchronized.
⚫ Java ArrayList allows random access because array works at the index basis.
⚫ In Java ArrayList class, manipulation is slow because a lot of shifting needs to
be occurred if any element is removed from the array list.
ArrayList class declaration Syntax:
public class ArrayList<E> extends AbstractList<E>
List<E>, RandomAccess, Clone able, Serializable
implements
OOPS_Unit2.inheritance and interface objected oriented programming
EXAMPLE
import java.util.*;
public class ArrayListExample1{
public static void main(String args[])
{ ArrayList<String> list=new ArrayList<String>();/
/Creating arraylist
list.add("Mango");//Adding object in arraylist
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//Printing the arraylist object
System.out.println(list);
} }
OUTPUT
 [Mango, Apple, Banana, Grapes]
ITERATING ARRAYLIST USING
ITERATOR
import java.util.*;
public class ArrayListExample2{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating
arraylist
list.add("Mango");//Adding object in arraylist
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//Traversing list through Iterator
Iterator itr=list.iterator();//getting the Iterator
while(itr.hasNext()){//check if iterator has the elements
System.out.println(itr.next());//printing the element and mo ve
to next
} } }
OUTPUT
 Mango
 Apple
 Banana
 Grapes
ITERATING ARRAYLIST USING FOR-EACH
LOOP
import java.util.*;
public class ArrayListExample3{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Cre
ating arraylist
list.add("Mango");//Adding object in arraylist
list.add("Apple");
list.add("Banana");
list.add("Grapes");
Collections.sort(list);
//Traversing list
through for-each
loop
for(String fruit:list)
System.out.println(fruit);
OUTPUT
 Mango
 Apple
 Banana
 Grapes
GET AND SET
ARRAYLIST
import java.util.*;
public class ArrayListExample4{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Mango");
al.add("Apple");
al.add("Banana");
al.add("Grapes");
//accessing the element
System.out.println("Returning element: "+al.get(1));//it will r
eturn the 2nd element, because index starts from 0
//changing the
element
al.set(1,"Dates");
//Traversing list
for(String fruit:al)
System.out.println(fruit);
} }
OUTPUT
 Returning element: Apple
 Mango
 Dates
 Banana
 Grapes
STRINGS IN JAVA
 In java, string is basically an object that represents sequence of char
values.
 Java String provides a lot of concepts that can be performed on a
replace,
string such as compare, concat, equals, split,
length,
compareTo, intern, substring etc.
 The java.lang.String class is used to create string object.
 In java, string objects are immutable.
 Immutable simply means unmodifiable or unchangeable.
String s=“Welcome to IT Dept";
CREATING THE STRING OBJECT
There are two ways to create String object:
1. By string literal
2. By new keyword
1) String Literal
Java String literal is created by using double quotes.
For Example:
String s="welcome";
2) By new keyword
String s=new String("Welcome");
STRING OBJECT
There are two ways to create String object:
1. By string literal
2. By new keyword
STRING LITERAL
 Java String literal is created by using double
quotes.
For Example:
⚫ String s1="welcome";
⚫ String s2=“welcome";
OOPS_Unit2.inheritance and interface objected oriented programming
BY NEW
KEYWORD
String s=new String("Welcome");
EXAMPLE
public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to str
ing
String s3=new String("example");//creating java string by
new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
OOPS_Unit2.inheritance and interface objected oriented programming
OOPS_Unit2.inheritance and interface objected oriented programming
OOPS_Unit2.inheritance and interface objected oriented programming

More Related Content

Similar to OOPS_Unit2.inheritance and interface objected oriented programming (20)

L04 Software Design 2
L04 Software Design 2
Ólafur Andri Ragnarsson
 
Java oops PPT
Java oops PPT
kishu0005
 
025466482929 -OOP with Java Development Kit.ppt
025466482929 -OOP with Java Development Kit.ppt
DakshinaPahan
 
02-OOP with Java.ppt
02-OOP with Java.ppt
EmanAsem4
 
java-06inheritance
java-06inheritance
Arjun Shanka
 
Lecture 6 inheritance
Lecture 6 inheritance
manish kumar
 
Modules 333333333³3444444444444444444.pptx
Modules 333333333³3444444444444444444.pptx
radhikacordise
 
20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles
Intro C# Book
 
Basic concept of class, method , command line-argument
Basic concept of class, method , command line-argument
Suresh Mohta
 
Java Basic day-2
Java Basic day-2
Kamlesh Singh
 
Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#
Abid Kohistani
 
Abstract class this is for ppt of JPR.pptx
Abstract class this is for ppt of JPR.pptx
CmDept
 
java program in Abstract class . pptx
java program in Abstract class . pptx
CmDept
 
Basics to java programming and concepts of java
Basics to java programming and concepts of java
1747503gunavardhanre
 
INHERITANCE.pptx
INHERITANCE.pptx
HARIPRIYA M P
 
Interface
Interface
Muthiah Abbhirami
 
Unit3 part2-inheritance
Unit3 part2-inheritance
DevaKumari Vijay
 
OOPS IN C++
OOPS IN C++
Amritsinghmehra
 
Chap-3 Inheritance.pptx
Chap-3 Inheritance.pptx
chetanpatilcp783
 
oops with java modules i & ii.ppt
oops with java modules i & ii.ppt
rani marri
 
Java oops PPT
Java oops PPT
kishu0005
 
025466482929 -OOP with Java Development Kit.ppt
025466482929 -OOP with Java Development Kit.ppt
DakshinaPahan
 
02-OOP with Java.ppt
02-OOP with Java.ppt
EmanAsem4
 
java-06inheritance
java-06inheritance
Arjun Shanka
 
Lecture 6 inheritance
Lecture 6 inheritance
manish kumar
 
Modules 333333333³3444444444444444444.pptx
Modules 333333333³3444444444444444444.pptx
radhikacordise
 
20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles
Intro C# Book
 
Basic concept of class, method , command line-argument
Basic concept of class, method , command line-argument
Suresh Mohta
 
Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#
Abid Kohistani
 
Abstract class this is for ppt of JPR.pptx
Abstract class this is for ppt of JPR.pptx
CmDept
 
java program in Abstract class . pptx
java program in Abstract class . pptx
CmDept
 
Basics to java programming and concepts of java
Basics to java programming and concepts of java
1747503gunavardhanre
 
oops with java modules i & ii.ppt
oops with java modules i & ii.ppt
rani marri
 

Recently uploaded (20)

OpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native Barcelona
Imma Valls Bernaus
 
GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?
felipeceotto
 
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
usmanch7829
 
Women in Tech: Marketo Engage User Group - June 2025 - AJO with AWS
Women in Tech: Marketo Engage User Group - June 2025 - AJO with AWS
BradBedford3
 
How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0
Anchore
 
IBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - Introduction
Gaurav Sharma
 
Software Testing & it’s types (DevOps)
Software Testing & it’s types (DevOps)
S Pranav (Deepu)
 
Plooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your way
Plooma
 
Agile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
Agentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Agentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Maxim Salnikov
 
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
Aarno Aukia
 
UPDASP a project coordination unit ......
UPDASP a project coordination unit ......
withrj1
 
FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Natan Silnitsky
 
Reimagining Software Development and DevOps with Agentic AI
Reimagining Software Development and DevOps with Agentic AI
Maxim Salnikov
 
Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)
VICTOR MAESTRE RAMIREZ
 
Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3
Gaurav Sharma
 
Who will create the languages of the future?
Who will create the languages of the future?
Jordi Cabot
 
Open Source Software Development Methods
Open Source Software Development Methods
VICTOR MAESTRE RAMIREZ
 
Generative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its Applications
SandeepKS52
 
OpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native Barcelona
Imma Valls Bernaus
 
GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?
felipeceotto
 
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
usmanch7829
 
Women in Tech: Marketo Engage User Group - June 2025 - AJO with AWS
Women in Tech: Marketo Engage User Group - June 2025 - AJO with AWS
BradBedford3
 
How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0
Anchore
 
IBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - Introduction
Gaurav Sharma
 
Software Testing & it’s types (DevOps)
Software Testing & it’s types (DevOps)
S Pranav (Deepu)
 
Plooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your way
Plooma
 
Agile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
Agentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Agentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Maxim Salnikov
 
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
Aarno Aukia
 
UPDASP a project coordination unit ......
UPDASP a project coordination unit ......
withrj1
 
FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Natan Silnitsky
 
Reimagining Software Development and DevOps with Agentic AI
Reimagining Software Development and DevOps with Agentic AI
Maxim Salnikov
 
Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)
VICTOR MAESTRE RAMIREZ
 
Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3
Gaurav Sharma
 
Who will create the languages of the future?
Who will create the languages of the future?
Jordi Cabot
 
Open Source Software Development Methods
Open Source Software Development Methods
VICTOR MAESTRE RAMIREZ
 
Generative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its Applications
SandeepKS52
 
Ad

OOPS_Unit2.inheritance and interface objected oriented programming

  • 2. UNIT II INHERITANCE AND INTERFACES Inheritance – Super classes- sub classes –Protected members – constructors in sub classes- the Object class – abstract classes and methods- final methods and classes – Interfaces – defining an interface, implementing interface, differences between classes and interfaces and extending interfaces - Object cloning -inner classes, ArrayLists - Strings
  • 3. INHERITANCE  When one object acquires all the properties and behaviors of a parent object, it is known as inheritance.  It provides code reusability. It is used to achieve runtime polymorphism.
  • 4. USES OF INHERITANCE IN JAV A o For Method Overriding. o For Code Reusability.  Syntax: class subClass extends superClass { //methods and fields }
  • 5. Method overloading: Void add(int a, int b) Void add(int a, int b, int c) Void add(float a,float b) Method Overriding: Void add(int a, int b) Void add(int a, int b)
  • 6. TYPES OF INHERITANCE  Single Inheritance  Multilevel Inheritance  Hierarchical inheritance.  Multiple & Hybrid inheritance is supported through interface only.
  • 8. 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 properties of 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 previous class.
  • 9. SINGLE INHERITANCE  When a class inherits another class, it is known as a single inheritance.
  • 11. MULTI LEVEL INHERITANCE Class B,A Class C,B,A
  • 14. HIERARCHICAL INHERITANCE class Animal { void eat(){ System.out.println("Anim als are eating"); } } class Dog extends Animal{ void eat1(){ System.out.println("Dog is eating"); } } class Cat extends Animal{ void eat2(){ System.out.println("Cat is eating"); } } class Deer extends Animal{ void eat3(){ System.out.println( "Deer is eating"); } } class Hi{ public static void main(String args[]) { Deer d1=new Deer(); d1.eat(); Cat c1=new Cat(); c1.eat2(); Dog d=new Dog(); d.eat1(); d1.eat3();
  • 16.  Multiple Inheritance and Hybrid Inheritance will be handled with the concept of interface.
  • 17. SUPER KEYWORD  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.
  • 18. USES OF SUPER KEYWORD Usage of super keyword 1. super() invokes the constructor of the parent class. 2. super.variable_name refers to the variable in the parent class. 3. super.method_name refers to the method of the parent class
  • 19. EXAMPL E class Animal { void eat(){ System.out.pri ntln("Animals are eating"); } } class Dog extends Animal{ void eat(){ System.out.println("Dog is eating"); super.eat();// here super keyword refers to the immediate parent class } class Super1{ public static void main(String args[]){
  • 21. 1) SUPER IS USED TO REFER IMMEDIATE PARENT CLASS INSTANCE VARIABLE. class Animal{ String color="white"; } class Dog extends Animal{ String color="black"; void printColor(){ System.out.println(color);// prints color of Dog class System.out.println(super.colo r);//prints color of Animal class } } class TestSuper1{ public static void main(String args[]){ Dog d=new Dog();
  • 23. 2) SUPER CAN BE USED TO INVOKE PARENT CLASS METHOD 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(); }}
  • 25. 3) SUPER IS USED TO INVOKE PARENT CLASS CONSTRUCTOR. 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(); }}
  • 26. class Person{ int id; String name; Person(int id,String name){ this.id=id; this.name=name; } } class Emp extends Person{ float salary; Emp(int id,String name,float salary) { super(id,name);//reusing parent constructor this.salary=salary; } void display(){System.out.println(id+" "+name+" "+salary);} } class TestSuper5{ public static void main(String[] args)
  • 27. PROTECTED MEMBERS  Protected data member and method are only accessible by the classes of the same package and the subclasses present in any package.  You can also say that the protected access modifier is similar to default access modifier with one exception that it has visibility in sub classes.  Classes cannot be declared protected.  This access modifier is generally used in a parent child relationship.
  • 28. EXAMPL E Addition.java package abcpackage; public class Addition { protected int addTwoNumbers(int a, int b) { return a+b; } } Test.java package xyzpackage; import abcpackage.*; class Test extends Addition{ public static void main(String args[]) { Test obj = new Test();
  • 29. THE OBJECT CLASS  There is one special class called Object, defined by Java.  All other classes are subclasses of Object.  That is, Object is a super class of all other classes.  This means that a reference variable of type Object can refer to an object of any other class.  Object defines the following methods, which means that they are available in every object.
  • 31. ABSTRACT CLASS  A class that is declared with abstract keyword, is known as abstract class in java.  The method which is defined inside the abstract class can be abstract method or non abstract method.
  • 33. ABSTRACT METHOD  The abstract class can also be used to provide some implementation of the interface.  In such case, the end user may not be forced to override all the methods of the interface.
  • 35. 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.
  • 37. DECLARATION OF INTERFACE  An interface is declared by using the interface keyword.  It provides total abstraction- means all the methods in an interface are declared with the empty body, and all the fields are public, static and final by default.  A class that implements an interface must implement all the methods declared in the interface.
  • 38. SYNTAX interface <interface_name>{ / / declare constant fields / / declare methods that abstract / / by default. }
  • 39. COMPILER POINT OF VIEW ABOUT INTERFACE
  • 40. EXAMPLE interface printable{ void print(); } class A6 implements printable{ public void print(){System.out.println("Hello");} public static void main(String args[]) { A6 obj = new A6(); obj.print(); } }
  • 41. interface Drawable{ void draw(); } //Implementation: by second user class Rectangle implements Drawable{ public void draw(){System.out.println("drawing rectangle");} } class Circle implements Drawable{ public void draw(){System.out.println("drawing circle");} } //Using interface: by third user class TestInterface1{ public static void main(String args[]){ Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawable() d.draw(); }}
  • 44.  Multiple inheritance in Java by interface .  If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as multiple inheritance. MULTIPLE INHERITANCE
  • 45. EXAMPLE 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(); } }
  • 46. EXAMPLE interface Printable{ void print(); } interface Showable extends Printable{ void show(); } class TestInterface4 implements Showable{ public void print(){System.out.println("Hello");} public void show(){System.out.println("Welcome");} public static void main(String args[]) { TestInterface4 obj = new TestInterface4(); obj.print(); obj.show(); } }
  • 47. HYBRID INHERITANCE  Hybrid Inheritance is a combination of both SingleInheritance and Multiple Inheritance.  Since in Java Multiple Inheritance supported directly we can achieve inheritance also through Interfaces only. is not Hybrid
  • 49. EXAMPLE public class ClassA { public void dispA() { System.out.println("disp() method of ClassA"); } } public interface InterfaceB { public void show(); } public interface InterfaceC { public void show(); } public class ClassD extends ClassA implements InterfaceB,InterfaceC { public void show() { System.out.println("show() method implementation"); }
  • 50. EXAMPLE public void dispD() { System.out.println("disp() method of ClassD"); } public static void main(String args[]) { ClassD d = new ClassD(); d.dispD(); d.show(); } }
  • 51. FINAL KEYWORD Final keyword can be used along with variables, methods and classes. 1) Final variable  A final variable is a variable whose value cannot be changed at anytime once assigned, it remains as a constant forever. 2) Final method  When you declare a method as final, then it is called as final method. A final method cannot be overridden. 3) Final class  A final class cannot be extended(cannot be subclassed)
  • 56. OBJECT CLONING  The object cloning is a way to create exact copy of an object.  The clone() method of Object class is used to clone an object.  The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create.  If we don't implement Cloneable interface, clone() method generates CloneNotSupportedException.  The clone() method is defined in the Object class. Syntax of the clone() method:  protected Object clone() throws CloneNotSupportedException
  • 58. INNER CLASSES  Java inner class or nested class is a class which is declared inside the class or interface.  We use inner classes to logically group classes and interfaces in one place so that it can be more readable and maintainable.  Additionally, it can access all the members of outer class including private data members and methods. Syntax of Inner class class Java_Outer_class{ //code class Java_Inner_class{ //code } }
  • 59. ADVANTAGE OF JAVA INNER CLASSES  There are basically three advantages of inner classes in java. They are as follows: ⚫ Nested classes represent a special type of relationship that is it can access all the members (data members and methods) of outer class including private. ⚫ Nested classes are used to develop more readable and maintainable code because it logically group classes and interfaces in one place only. ⚫ Code Optimization: It requires less code to write.
  • 60. TYPES OF NESTED CLASSES  There are two types of nested classes non-static and static nested classes.  The non-static nested classes are also known as inner classes. 1) Non-static nested class (inner class)  Member inner class  Anonymous inner class  Local inner class 2) Static nested class
  • 61. TYPES OF NESTED CLASSES Type Description Member Inner Class A class created within class and outside method. Anonymous Inner Class A class created for implementing interface or extending class. Its name is decided by the java compiler. Local Inner Class A class created within method. Static Nested Class A static class created within class. Nested Interface An interface created within class or interface.
  • 62. 1. JAVA MEMBER INNER CLASS class TestMemberOuter1{ privat e int data=30; class Inner{ void msg() {System.out.println("data is "+data);} } public static void main(String args[]) { TestMemberOuter1 obj=new TestMemberOuter1( ); TestMemberOuter1.Inner in=obj.new Inner(); in.msg();
  • 63. 2. ANONYMOUS INNER CLASS  A class that have no name is known as anonymous inner class in java.  It should be used if you have to override method of class or interface.  Java Anonymous inner class can be created by two ways: 1. Class (may be abstract or concrete). 2. Interface
  • 64. 2.1 JAVA ANONYMOUS INNER CLASS EXAMPLE USING CLASS abstract class Person{ abstract void eat(); } class TestAnonymousInner{ public static void main(String args[]) { Person p=new Person(){ void eat(){System.out.println("nice fruits");} }; p.eat(); } }
  • 65. 2.2 JAVA ANONYMOUS INNER CLASS EXAMPLE USING INTERFACE interface Eatable{ void eat(); } class TestAnno{ public static void main(String args[]) { Eatable e=new Eatable(){ public void eat() {System.out.println("nice fruits" );} }; e.eat(); } }
  • 66. 3. LOCAL INNER CLASS  A class i.e. created inside a method is called local inner class in java.  If you want to invoke the methods of local inner class, you must instantiate this class inside the method.
  • 67. JAVA LOCAL INNER CLASS EXAMPLE public class localInner1{ private int data=30;//instance variable void display(){ class Local{ void msg(){System.out.println(data);} } Local l=new Local(); l.msg(); } public static void main(String args[]){ localInner1 obj=new localInner1(); obj.display(); }
  • 68. EXAMPLE OF LOCAL INNER CLASS WITH LOCAL VARIABLE class localInner2{ private int data=30;//instance variable void display(){ int value=50;//local variable must be final till jdk 1.7 only class Local{ void msg(){System.out.println(value);} } Local l=new Local(); l.msg(); } public static void main(String args[]){ localInner2 obj=new localInner2(); obj.display(); }
  • 69. 4. JAVA STATIC NESTED CLASS  A static class i.e. created inside a class is called static nested class in java.  It cannot access non-static data members and methods.  It can be accessed by outer class name.  It can access static data members of outer class including private.  Static nested class cannot access non- static (instance) data member or method.
  • 70. JAVA STATIC NESTED CLASS EXAMPLE WITH INSTANCE METHOD class TestOuter1{ static int data=30; static class Inner{ void msg() {System.out.println ("data is "+data);} } public static void main(String args[]) { TestOuter1.Inner obj=new TestOuter1.Inner(); obj.msg(); }
  • 71. JAVA ARRAYLIST CLASS  Java ArrayList class uses a dynamic array for storing the elements.  It inherits AbstractList class and implements List interface.  The important points about Java ArrayList class are: ⚫ Java ArrayList class can contain duplicate elements. ⚫ Java ArrayList class maintains insertion order. ⚫ Java ArrayList class is non synchronized. ⚫ Java ArrayList allows random access because array works at the index basis. ⚫ In Java ArrayList class, manipulation is slow because a lot of shifting needs to be occurred if any element is removed from the array list. ArrayList class declaration Syntax: public class ArrayList<E> extends AbstractList<E> List<E>, RandomAccess, Clone able, Serializable implements
  • 73. EXAMPLE import java.util.*; public class ArrayListExample1{ public static void main(String args[]) { ArrayList<String> list=new ArrayList<String>();/ /Creating arraylist list.add("Mango");//Adding object in arraylist list.add("Apple"); list.add("Banana"); list.add("Grapes"); //Printing the arraylist object System.out.println(list); } }
  • 74. OUTPUT  [Mango, Apple, Banana, Grapes]
  • 75. ITERATING ARRAYLIST USING ITERATOR import java.util.*; public class ArrayListExample2{ public static void main(String args[]){ ArrayList<String> list=new ArrayList<String>();//Creating arraylist list.add("Mango");//Adding object in arraylist list.add("Apple"); list.add("Banana"); list.add("Grapes"); //Traversing list through Iterator Iterator itr=list.iterator();//getting the Iterator while(itr.hasNext()){//check if iterator has the elements System.out.println(itr.next());//printing the element and mo ve to next } } }
  • 76. OUTPUT  Mango  Apple  Banana  Grapes
  • 77. ITERATING ARRAYLIST USING FOR-EACH LOOP import java.util.*; public class ArrayListExample3{ public static void main(String args[]){ ArrayList<String> list=new ArrayList<String>();//Cre ating arraylist list.add("Mango");//Adding object in arraylist list.add("Apple"); list.add("Banana"); list.add("Grapes"); Collections.sort(list); //Traversing list through for-each loop for(String fruit:list) System.out.println(fruit);
  • 78. OUTPUT  Mango  Apple  Banana  Grapes
  • 79. GET AND SET ARRAYLIST import java.util.*; public class ArrayListExample4{ public static void main(String args[]){ ArrayList<String> al=new ArrayList<String>(); al.add("Mango"); al.add("Apple"); al.add("Banana"); al.add("Grapes"); //accessing the element System.out.println("Returning element: "+al.get(1));//it will r eturn the 2nd element, because index starts from 0 //changing the element al.set(1,"Dates"); //Traversing list for(String fruit:al) System.out.println(fruit); } }
  • 80. OUTPUT  Returning element: Apple  Mango  Dates  Banana  Grapes
  • 81. STRINGS IN JAVA  In java, string is basically an object that represents sequence of char values.  Java String provides a lot of concepts that can be performed on a replace, string such as compare, concat, equals, split, length, compareTo, intern, substring etc.  The java.lang.String class is used to create string object.  In java, string objects are immutable.  Immutable simply means unmodifiable or unchangeable. String s=“Welcome to IT Dept";
  • 82. CREATING THE STRING OBJECT There are two ways to create String object: 1. By string literal 2. By new keyword 1) String Literal Java String literal is created by using double quotes. For Example: String s="welcome"; 2) By new keyword String s=new String("Welcome");
  • 83. STRING OBJECT There are two ways to create String object: 1. By string literal 2. By new keyword
  • 84. STRING LITERAL  Java String literal is created by using double quotes. For Example: ⚫ String s1="welcome"; ⚫ String s2=“welcome";
  • 86. BY NEW KEYWORD String s=new String("Welcome");
  • 87. EXAMPLE public class StringExample{ public static void main(String args[]){ String s1="java";//creating string by java string literal char ch[]={'s','t','r','i','n','g','s'}; String s2=new String(ch);//converting char array to str ing String s3=new String("example");//creating java string by new keyword System.out.println(s1); System.out.println(s2); System.out.println(s3); }}