SlideShare a Scribd company logo
1 of 32
Java/J2EE Programming Training
OOP with Java Contd.
Page 2Classification: Restricted
Agenda
• Review of last class concepts
• Types of Inheritance and a look at Aggregation
• Polymorphism
• Method overloading
• Method overriding
Inheritance in Java
• a mechanism in which one object acquires all the properties and
behaviours
of parent object.
• Inheritance represents the IS-A relationship, also known as parent-
child relationship.
• Why use inheritance in java
oFor Method Overriding (so runtime polymorphism can be achieved).
oFor Code Reusability.
Classification: Restricted Page 3
Inheritance in Java
Classification: Restricted Page 4
Types of Inheritance
Classification: Restricted Page 5
Inheritance Not Supported in Java
• When a class extends multiple classes i.e. known as multiple inheritance.
Classification: Restricted Page 6
Why multiple inheritance not supported in Java?
Classification: Restricted Page 7
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? Compile-time
error
}
}
Aggregation in Java
• If a class have an entity reference, it is known as Aggregation.
• Aggregation represents HAS-A relationship.
• Why use Aggregation?
oFor Code Reusability.
Classification: Restricted Page 8
Aggregation in Java
Classification: Restricted Page 9
class Operation{
int square(int n){
return n*n;
}
}
class Circle{
Operation op;//aggregation
double pi=3.14;
double area(int radius){
op=new Operation();
int rsquare=op.square(radius);//code reusability (i.e. delegates the method call).
return pi*rsquare;
}
public static void main(String args[]){
Circle c=new Circle();
double result=c.area(5);
System.out.println(result);
}
}
Example: Employee HAS-A Address
Classification: Restricted Page 10
• Demo
Method Overriding in Java
Classification: Restricted Page 12
• If subclass (child class) has the same method as declared in the parent
class, it is known as method overriding in java.
• If subclass provides the specific implementation of the method that has
been provided by one of its parent class, it is known as method overriding.
• Method overriding is used to provide specific implementation of a
method that is already provided by its super class.
• Method overriding is used for runtime polymorphism
• Rules:
• method must have same name as in the parent class
• method must have same parameter as in the parent class.
• must be IS-A relationship (inheritance).
Example of Method Overriding
Classification: Restricted Page 13
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike2 extends Vehicle{
void run(){System.out.println("Bike is running safely");}
public static void main(String args[]){ Bike2
obj = new Bike2(); obj.run();
}
Classification: Restricted Page 14
Point to ponder.. Can we override static methods in Java? Why?
Think… (This is one of the exercises for today)
Method Overloading vs Method Overriding
Classification: Restricted Page 15
No. Method Overloading Method Overriding
1) Method overloading is used to
increase the readability of the
program.
Method overriding is used to provide the
specific implementation of the method that
is already provided by its super class.
2) Method overloading can be
performed within class.
Method overriding occurs in two classes
that have IS-A (inheritance) relationship.
3) In case of method overloading,
parameter must be different.
In case of method overriding, parameter
must be same.
4) Method overloading is the example
of compile time polymorphism.
Method overriding is the example of run
time polymorphism.
5) In Java, method overloading can't be
performed by changing return type of
the method only. Return type can be
same or different in method
overloading. But you must have to
change the parameter.
Return type must be same or covariant in
method overriding.
super keyword in Java
Classification: Restricted Page 16
• The super keyword in Java is a reference variable that is used to refer
immediate parent class object.
• Usage of super Keyword
o super is used to refer immediate parent class instancevariable.
o super() is used to invoke immediate parent classconstructor.
o super is used to invoke immediate parent classmethod.
super used to refer immediate parent class instance variable
class Vehicle{
int speed=50;
}
class Bike3 extends Vehicle{
int speed=100;
void display(){
System.out.println(speed);//will print speed of Bike
System.out.println(super.speed);//will print speed of Vehicle
}
public static void main(String args[]){
Bike3 b=new Bike3();
b.display();
}
}
Classification: Restricted Page 17
super is used to invoke parent class constructor
Classification: Restricted Page 18
class Vehicle{
Vehicle(){System.out.println("Vehicle is created");}
}
class Bike5 extends Vehicle{
Bike5(){
super();//will invoke parent class constructor
System.out.println("Bike is created");
}
public static void main(String args[]){
Bike5 b=new Bike5();
}
}
super can be used to invoke parent class method
Classification: Restricted Page 19
class Person{
void message(){System.out.println("welcome");}
}
class Student16 extends Person{
void message(){System.out.println("welcome to java");}
void display(){
message();//will invoke current class message() method
super.message();//will invoke parent class message() method
}
public static void main(String args[]){ Student16
s=new Student16(); s.display();
}
}
super not required here
Classification: Restricted Page 20
class Person{
void message(){System.out.println("welcome");}
}
class Student17 extends Person{ void
display(){
message();//will invoke parent class message() method
}
public static void main(String args[]){ Student17
s=new Student17(); s.display();
}
}
final keyword in Java
Classification: Restricted Page 22
• final keyword applied to
• Variable: stops value change
• Methods: stops overriding
• Class: stops inheritance
final variable
Classification: Restricted Page 23
final variable once assigned a value can never be changed.
class Bike9{
final int speedlimit=90;//final variable void
run(){
speedlimit=400; //compile-time error
}
public static void main(String args[]){ Bike9
obj=new Bike9();
obj.run();
}
}//end of class
final method – cannot override
Classification: Restricted Page 24
class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");}
//compile-time error
public static void main(String args[]){ Honda
honda = new Honda(); honda.run();
}
}
final class – cannot extend
Classification: Restricted Page 25
final class Bike{}
class Honda1 extends Bike{ //compile-time error
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){ Honda1
honda= new Honda(); honda.run();
}
}
Blank final variables must be initialized only in constructor
Classification: Restricted Page 26
class Bike10{
final int speedlimit; // blank final variable
Bike10(){
speedlimit=70; // initialized in constructor
System.out.println(speedlimit);
}
public static void main(String args[]){ new
Bike10();
}
}
final parameter example
Classification: Restricted Page 27
class Bike11{
int cube(final int n){
n=n+2; //can't be changed as n is final
n*n*n;
}
public static void main(String args[]){
Bike11 b=new Bike11();
b.cube(5);
}
}
Point to ponder…Can constructors be declared final?
Classification: Restricted Page 28
Think… (Exercise for today)
Java Runtime Polymorphism – Example of Upcasting
Classification: Restricted Page 29
class Animal{
void eat(){System.out.println("eating");}
}
class Dog extends Animal{
void eat(){System.out.println("eating fruits");}
}
class BabyDog extends Dog{
void eat(){System.out.println("drinking milk");}
public static void main(String args[]){ Animal a1,a2,a3;
a1=new Animal();
a2=new Dog();
a3=new BabyDog();
a1.eat();
a2.eat();
a3.eat();
}
}
Static and dynamic binding
Classification: Restricted Page 30
Static Binding: Type of object determined at Compile time.
class Dog{
private void eat(){System.out.println("dog is eating...");}
public static void main(String
args[]){ Dog d1=new Dog();
d1.eat();
}
}
Dynamic Binding: Type of object determined at run time
class Animal{
void eat(){System.out.println("animal is eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("dog is eating...");}
public static void main(String
args[]){ Animal a=new Dog();
a.eat();
}
}
instanceof operator
Classification: Restricted Page 31
• used to test whether the object is an instance of the specified type (class or
subclass or interface).
class Simple1{
public static void main(String args[]){
Simple1 s=new Simple1();
System.out.println(s instanceof Simple1);//true
}
}
class Animal{}
class Dog1 extends Animal{//Dog inherits Animal
public static void main(String args[]){
Dog1 d=new Dog1();
System.out.println(d instanceof Animal);//true
}
}
class Dog2{
public static void main(String args[]){
Dog2 d=null;
System.out.println(d instanceof Dog2);//false
}
}
Classification: Restricted Page 32
instanceof operator
Downcasting
Classification: Restricted Page 33
Dog d=new Animal();//Compilation error
Dog d=(Dog)new Animal();
//Compiles successfully but ClassCastException could be thrown
at runtime
Thank You

More Related Content

What's hot

OOP with Java - Continued
OOP with Java - Continued OOP with Java - Continued
OOP with Java - Continued Hitesh-Java
 
Session 01 - Introduction to Java
Session 01 - Introduction to JavaSession 01 - Introduction to Java
Session 01 - Introduction to JavaPawanMM
 
Java SE 9 modules - an introduction (July 2018)
Java SE 9 modules - an introduction (July 2018)Java SE 9 modules - an introduction (July 2018)
Java SE 9 modules - an introduction (July 2018)Stephen Colebourne
 
Java Classes methods and inheritance
Java Classes methods and inheritanceJava Classes methods and inheritance
Java Classes methods and inheritanceSrinivas Reddy
 
Exception Handling - Continued
Exception Handling - Continued Exception Handling - Continued
Exception Handling - Continued Hitesh-Java
 
Java Classes | Java Tutorial for Beginners | Java Classes and Objects | Java ...
Java Classes | Java Tutorial for Beginners | Java Classes and Objects | Java ...Java Classes | Java Tutorial for Beginners | Java Classes and Objects | Java ...
Java Classes | Java Tutorial for Beginners | Java Classes and Objects | Java ...Edureka!
 
Java interview questions 1
Java interview questions 1Java interview questions 1
Java interview questions 1Sherihan Anver
 
Interactive Java Support to your tool -- The JShell API and Architecture
Interactive Java Support to your tool -- The JShell API and ArchitectureInteractive Java Support to your tool -- The JShell API and Architecture
Interactive Java Support to your tool -- The JShell API and ArchitectureJavaDayUA
 
Hibernate introduction
Hibernate introductionHibernate introduction
Hibernate introductionSagar Verma
 
JShell: An Interactive Shell for the Java Platform
JShell: An Interactive Shell for the Java PlatformJShell: An Interactive Shell for the Java Platform
JShell: An Interactive Shell for the Java PlatformJavaDayUA
 
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov Nayden Gochev
 
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...Sagar Verma
 
PROGRAMMING IN JAVA-unit 3-part II
PROGRAMMING IN JAVA-unit 3-part IIPROGRAMMING IN JAVA-unit 3-part II
PROGRAMMING IN JAVA-unit 3-part IISivaSankari36
 
Playing with Java Classes and Bytecode
Playing with Java Classes and BytecodePlaying with Java Classes and Bytecode
Playing with Java Classes and BytecodeYoav Avrahami
 
Java 8 selected updates
Java 8 selected updatesJava 8 selected updates
Java 8 selected updatesVinay H G
 
Java Programming | Java Tutorial For Beginners | Java Training | Edureka
Java Programming | Java Tutorial For Beginners | Java Training | EdurekaJava Programming | Java Tutorial For Beginners | Java Training | Edureka
Java Programming | Java Tutorial For Beginners | Java Training | EdurekaEdureka!
 

What's hot (20)

Inner Classes
Inner Classes Inner Classes
Inner Classes
 
OOP with Java - Continued
OOP with Java - Continued OOP with Java - Continued
OOP with Java - Continued
 
Session 01 - Introduction to Java
Session 01 - Introduction to JavaSession 01 - Introduction to Java
Session 01 - Introduction to Java
 
Java SE 9 modules - an introduction (July 2018)
Java SE 9 modules - an introduction (July 2018)Java SE 9 modules - an introduction (July 2018)
Java SE 9 modules - an introduction (July 2018)
 
Java Classes methods and inheritance
Java Classes methods and inheritanceJava Classes methods and inheritance
Java Classes methods and inheritance
 
Exception Handling - Continued
Exception Handling - Continued Exception Handling - Continued
Exception Handling - Continued
 
Java Classes | Java Tutorial for Beginners | Java Classes and Objects | Java ...
Java Classes | Java Tutorial for Beginners | Java Classes and Objects | Java ...Java Classes | Java Tutorial for Beginners | Java Classes and Objects | Java ...
Java Classes | Java Tutorial for Beginners | Java Classes and Objects | Java ...
 
Java interview questions 1
Java interview questions 1Java interview questions 1
Java interview questions 1
 
Interactive Java Support to your tool -- The JShell API and Architecture
Interactive Java Support to your tool -- The JShell API and ArchitectureInteractive Java Support to your tool -- The JShell API and Architecture
Interactive Java Support to your tool -- The JShell API and Architecture
 
Hibernate introduction
Hibernate introductionHibernate introduction
Hibernate introduction
 
JShell: An Interactive Shell for the Java Platform
JShell: An Interactive Shell for the Java PlatformJShell: An Interactive Shell for the Java Platform
JShell: An Interactive Shell for the Java Platform
 
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
 
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
 
Basics of Java
Basics of JavaBasics of Java
Basics of Java
 
PROGRAMMING IN JAVA-unit 3-part II
PROGRAMMING IN JAVA-unit 3-part IIPROGRAMMING IN JAVA-unit 3-part II
PROGRAMMING IN JAVA-unit 3-part II
 
Playing with Java Classes and Bytecode
Playing with Java Classes and BytecodePlaying with Java Classes and Bytecode
Playing with Java Classes and Bytecode
 
Core java
Core javaCore java
Core java
 
Java 8 selected updates
Java 8 selected updatesJava 8 selected updates
Java 8 selected updates
 
Java Programming | Java Tutorial For Beginners | Java Training | Edureka
Java Programming | Java Tutorial For Beginners | Java Training | EdurekaJava Programming | Java Tutorial For Beginners | Java Training | Edureka
Java Programming | Java Tutorial For Beginners | Java Training | Edureka
 
Invoke dynamics
Invoke dynamicsInvoke dynamics
Invoke dynamics
 

Similar to OOP with Java - Part 3

Session 09 - OOP with Java - Part 3
Session 09 - OOP with Java - Part 3Session 09 - OOP with Java - Part 3
Session 09 - OOP with Java - Part 3PawanMM
 
OOPs Concepts - Android Programming
OOPs Concepts - Android ProgrammingOOPs Concepts - Android Programming
OOPs Concepts - Android ProgrammingPurvik Rana
 
Session 10 - OOP with Java - Abstract Classes and Interfaces
Session 10 - OOP with Java - Abstract Classes and InterfacesSession 10 - OOP with Java - Abstract Classes and Interfaces
Session 10 - OOP with Java - Abstract Classes and InterfacesPawanMM
 
OOP with Java - Abstract Classes and Interfaces
OOP with Java - Abstract Classes and InterfacesOOP with Java - Abstract Classes and Interfaces
OOP with Java - Abstract Classes and InterfacesRatnaJava
 
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi (gandhiri@gmail.com)Gandhi Ravi
 
Java non access modifiers
Java non access modifiersJava non access modifiers
Java non access modifiersSrinivas Reddy
 
oops with java modules i & ii.ppt
oops with java modules i & ii.pptoops with java modules i & ii.ppt
oops with java modules i & ii.pptrani marri
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satyaSatya Johnny
 
04 Java Language And OOP Part IV
04 Java Language And OOP Part IV04 Java Language And OOP Part IV
04 Java Language And OOP Part IVHari Christian
 
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAdvanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAVINASH KUMAR
 
Object Orinted Programing(OOP) concepts \
Object Orinted Programing(OOP) concepts \Object Orinted Programing(OOP) concepts \
Object Orinted Programing(OOP) concepts \Pritom Chaki
 
java: basics, user input, data type, constructor
java:  basics, user input, data type, constructorjava:  basics, user input, data type, constructor
java: basics, user input, data type, constructorShivam Singhal
 
Lecture5_Method_overloading_Final power point presentation
Lecture5_Method_overloading_Final power point presentationLecture5_Method_overloading_Final power point presentation
Lecture5_Method_overloading_Final power point presentationbhargavi804095
 
Lecture4_Method_overloading power point presentaion
Lecture4_Method_overloading power point presentaionLecture4_Method_overloading power point presentaion
Lecture4_Method_overloading power point presentaionbhargavi804095
 

Similar to OOP with Java - Part 3 (20)

Session 09 - OOP with Java - Part 3
Session 09 - OOP with Java - Part 3Session 09 - OOP with Java - Part 3
Session 09 - OOP with Java - Part 3
 
OOPs Concepts - Android Programming
OOPs Concepts - Android ProgrammingOOPs Concepts - Android Programming
OOPs Concepts - Android Programming
 
Inheritance1
Inheritance1Inheritance1
Inheritance1
 
Session 10 - OOP with Java - Abstract Classes and Interfaces
Session 10 - OOP with Java - Abstract Classes and InterfacesSession 10 - OOP with Java - Abstract Classes and Interfaces
Session 10 - OOP with Java - Abstract Classes and Interfaces
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
OOP with Java - Abstract Classes and Interfaces
OOP with Java - Abstract Classes and InterfacesOOP with Java - Abstract Classes and Interfaces
OOP with Java - Abstract Classes and Interfaces
 
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi (gandhiri@gmail.com)
 
Chap-3 Inheritance.pptx
Chap-3 Inheritance.pptxChap-3 Inheritance.pptx
Chap-3 Inheritance.pptx
 
Java non access modifiers
Java non access modifiersJava non access modifiers
Java non access modifiers
 
oops with java modules i & ii.ppt
oops with java modules i & ii.pptoops with java modules i & ii.ppt
oops with java modules i & ii.ppt
 
Adv kvr -satya
Adv  kvr -satyaAdv  kvr -satya
Adv kvr -satya
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satya
 
11.Object Oriented Programming.pdf
11.Object Oriented Programming.pdf11.Object Oriented Programming.pdf
11.Object Oriented Programming.pdf
 
04 Java Language And OOP Part IV
04 Java Language And OOP Part IV04 Java Language And OOP Part IV
04 Java Language And OOP Part IV
 
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAdvanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
 
Object Orinted Programing(OOP) concepts \
Object Orinted Programing(OOP) concepts \Object Orinted Programing(OOP) concepts \
Object Orinted Programing(OOP) concepts \
 
java: basics, user input, data type, constructor
java:  basics, user input, data type, constructorjava:  basics, user input, data type, constructor
java: basics, user input, data type, constructor
 
Inheritance and Interfaces
Inheritance and InterfacesInheritance and Interfaces
Inheritance and Interfaces
 
Lecture5_Method_overloading_Final power point presentation
Lecture5_Method_overloading_Final power point presentationLecture5_Method_overloading_Final power point presentation
Lecture5_Method_overloading_Final power point presentation
 
Lecture4_Method_overloading power point presentaion
Lecture4_Method_overloading power point presentaionLecture4_Method_overloading power point presentaion
Lecture4_Method_overloading power point presentaion
 

More from RatnaJava

Review Session and Attending Java Interviews
Review Session and Attending Java InterviewsReview Session and Attending Java Interviews
Review Session and Attending Java InterviewsRatnaJava
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & setsRatnaJava
 
Collections - Sorting, Comparing Basics
Collections - Sorting, Comparing BasicsCollections - Sorting, Comparing Basics
Collections - Sorting, Comparing BasicsRatnaJava
 
Collections Array list
Collections Array listCollections Array list
Collections Array listRatnaJava
 
Object Class
Object ClassObject Class
Object ClassRatnaJava
 
Exception Handling
Exception Handling  Exception Handling
Exception Handling RatnaJava
 
OOPs with Java - Packaging and Access Modifiers
OOPs with Java - Packaging and Access ModifiersOOPs with Java - Packaging and Access Modifiers
OOPs with Java - Packaging and Access ModifiersRatnaJava
 
OOP with Java - continued
OOP with Java - continuedOOP with Java - continued
OOP with Java - continuedRatnaJava
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented ProgrammingRatnaJava
 
Data Handling and Function
Data Handling and FunctionData Handling and Function
Data Handling and FunctionRatnaJava
 
Introduction to Java Part-3
Introduction to Java Part-3Introduction to Java Part-3
Introduction to Java Part-3RatnaJava
 
Introduction to Java Part-2
Introduction to Java Part-2Introduction to Java Part-2
Introduction to Java Part-2RatnaJava
 
Introduction to Java
Introduction to Java Introduction to Java
Introduction to Java RatnaJava
 

More from RatnaJava (13)

Review Session and Attending Java Interviews
Review Session and Attending Java InterviewsReview Session and Attending Java Interviews
Review Session and Attending Java Interviews
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & sets
 
Collections - Sorting, Comparing Basics
Collections - Sorting, Comparing BasicsCollections - Sorting, Comparing Basics
Collections - Sorting, Comparing Basics
 
Collections Array list
Collections Array listCollections Array list
Collections Array list
 
Object Class
Object ClassObject Class
Object Class
 
Exception Handling
Exception Handling  Exception Handling
Exception Handling
 
OOPs with Java - Packaging and Access Modifiers
OOPs with Java - Packaging and Access ModifiersOOPs with Java - Packaging and Access Modifiers
OOPs with Java - Packaging and Access Modifiers
 
OOP with Java - continued
OOP with Java - continuedOOP with Java - continued
OOP with Java - continued
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented Programming
 
Data Handling and Function
Data Handling and FunctionData Handling and Function
Data Handling and Function
 
Introduction to Java Part-3
Introduction to Java Part-3Introduction to Java Part-3
Introduction to Java Part-3
 
Introduction to Java Part-2
Introduction to Java Part-2Introduction to Java Part-2
Introduction to Java Part-2
 
Introduction to Java
Introduction to Java Introduction to Java
Introduction to Java
 

Recently uploaded

08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 

Recently uploaded (20)

08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 

OOP with Java - Part 3

  • 2. Page 2Classification: Restricted Agenda • Review of last class concepts • Types of Inheritance and a look at Aggregation • Polymorphism • Method overloading • Method overriding
  • 3. Inheritance in Java • a mechanism in which one object acquires all the properties and behaviours of parent object. • Inheritance represents the IS-A relationship, also known as parent- child relationship. • Why use inheritance in java oFor Method Overriding (so runtime polymorphism can be achieved). oFor Code Reusability. Classification: Restricted Page 3
  • 6. Inheritance Not Supported in Java • When a class extends multiple classes i.e. known as multiple inheritance. Classification: Restricted Page 6
  • 7. Why multiple inheritance not supported in Java? Classification: Restricted Page 7 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? Compile-time error } }
  • 8. Aggregation in Java • If a class have an entity reference, it is known as Aggregation. • Aggregation represents HAS-A relationship. • Why use Aggregation? oFor Code Reusability. Classification: Restricted Page 8
  • 9. Aggregation in Java Classification: Restricted Page 9 class Operation{ int square(int n){ return n*n; } } class Circle{ Operation op;//aggregation double pi=3.14; double area(int radius){ op=new Operation(); int rsquare=op.square(radius);//code reusability (i.e. delegates the method call). return pi*rsquare; } public static void main(String args[]){ Circle c=new Circle(); double result=c.area(5); System.out.println(result); } }
  • 10. Example: Employee HAS-A Address Classification: Restricted Page 10 • Demo
  • 11. Method Overriding in Java Classification: Restricted Page 12 • If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java. • If subclass provides the specific implementation of the method that has been provided by one of its parent class, it is known as method overriding. • Method overriding is used to provide specific implementation of a method that is already provided by its super class. • Method overriding is used for runtime polymorphism • Rules: • method must have same name as in the parent class • method must have same parameter as in the parent class. • must be IS-A relationship (inheritance).
  • 12. Example of Method Overriding Classification: Restricted Page 13 class Vehicle{ void run(){System.out.println("Vehicle is running");} } class Bike2 extends Vehicle{ void run(){System.out.println("Bike is running safely");} public static void main(String args[]){ Bike2 obj = new Bike2(); obj.run(); }
  • 13. Classification: Restricted Page 14 Point to ponder.. Can we override static methods in Java? Why? Think… (This is one of the exercises for today)
  • 14. Method Overloading vs Method Overriding Classification: Restricted Page 15 No. Method Overloading Method Overriding 1) Method overloading is used to increase the readability of the program. Method overriding is used to provide the specific implementation of the method that is already provided by its super class. 2) Method overloading can be performed within class. Method overriding occurs in two classes that have IS-A (inheritance) relationship. 3) In case of method overloading, parameter must be different. In case of method overriding, parameter must be same. 4) Method overloading is the example of compile time polymorphism. Method overriding is the example of run time polymorphism. 5) In Java, method overloading can't be performed by changing return type of the method only. Return type can be same or different in method overloading. But you must have to change the parameter. Return type must be same or covariant in method overriding.
  • 15. super keyword in Java Classification: Restricted Page 16 • The super keyword in Java is a reference variable that is used to refer immediate parent class object. • Usage of super Keyword o super is used to refer immediate parent class instancevariable. o super() is used to invoke immediate parent classconstructor. o super is used to invoke immediate parent classmethod.
  • 16. super used to refer immediate parent class instance variable class Vehicle{ int speed=50; } class Bike3 extends Vehicle{ int speed=100; void display(){ System.out.println(speed);//will print speed of Bike System.out.println(super.speed);//will print speed of Vehicle } public static void main(String args[]){ Bike3 b=new Bike3(); b.display(); } } Classification: Restricted Page 17
  • 17. super is used to invoke parent class constructor Classification: Restricted Page 18 class Vehicle{ Vehicle(){System.out.println("Vehicle is created");} } class Bike5 extends Vehicle{ Bike5(){ super();//will invoke parent class constructor System.out.println("Bike is created"); } public static void main(String args[]){ Bike5 b=new Bike5(); } }
  • 18. super can be used to invoke parent class method Classification: Restricted Page 19 class Person{ void message(){System.out.println("welcome");} } class Student16 extends Person{ void message(){System.out.println("welcome to java");} void display(){ message();//will invoke current class message() method super.message();//will invoke parent class message() method } public static void main(String args[]){ Student16 s=new Student16(); s.display(); } }
  • 19. super not required here Classification: Restricted Page 20 class Person{ void message(){System.out.println("welcome");} } class Student17 extends Person{ void display(){ message();//will invoke parent class message() method } public static void main(String args[]){ Student17 s=new Student17(); s.display(); } }
  • 20. final keyword in Java Classification: Restricted Page 22 • final keyword applied to • Variable: stops value change • Methods: stops overriding • Class: stops inheritance
  • 21. final variable Classification: Restricted Page 23 final variable once assigned a value can never be changed. class Bike9{ final int speedlimit=90;//final variable void run(){ speedlimit=400; //compile-time error } public static void main(String args[]){ Bike9 obj=new Bike9(); obj.run(); } }//end of class
  • 22. final method – cannot override Classification: Restricted Page 24 class Bike{ final void run(){System.out.println("running");} } class Honda extends Bike{ void run(){System.out.println("running safely with 100kmph");} //compile-time error public static void main(String args[]){ Honda honda = new Honda(); honda.run(); } }
  • 23. final class – cannot extend Classification: Restricted Page 25 final class Bike{} class Honda1 extends Bike{ //compile-time error void run(){System.out.println("running safely with 100kmph");} public static void main(String args[]){ Honda1 honda= new Honda(); honda.run(); } }
  • 24. Blank final variables must be initialized only in constructor Classification: Restricted Page 26 class Bike10{ final int speedlimit; // blank final variable Bike10(){ speedlimit=70; // initialized in constructor System.out.println(speedlimit); } public static void main(String args[]){ new Bike10(); } }
  • 25. final parameter example Classification: Restricted Page 27 class Bike11{ int cube(final int n){ n=n+2; //can't be changed as n is final n*n*n; } public static void main(String args[]){ Bike11 b=new Bike11(); b.cube(5); } }
  • 26. Point to ponder…Can constructors be declared final? Classification: Restricted Page 28 Think… (Exercise for today)
  • 27. Java Runtime Polymorphism – Example of Upcasting Classification: Restricted Page 29 class Animal{ void eat(){System.out.println("eating");} } class Dog extends Animal{ void eat(){System.out.println("eating fruits");} } class BabyDog extends Dog{ void eat(){System.out.println("drinking milk");} public static void main(String args[]){ Animal a1,a2,a3; a1=new Animal(); a2=new Dog(); a3=new BabyDog(); a1.eat(); a2.eat(); a3.eat(); } }
  • 28. Static and dynamic binding Classification: Restricted Page 30 Static Binding: Type of object determined at Compile time. class Dog{ private void eat(){System.out.println("dog is eating...");} public static void main(String args[]){ Dog d1=new Dog(); d1.eat(); } } Dynamic Binding: Type of object determined at run time class Animal{ void eat(){System.out.println("animal is eating...");} } class Dog extends Animal{ void eat(){System.out.println("dog is eating...");} public static void main(String args[]){ Animal a=new Dog(); a.eat(); } }
  • 29. instanceof operator Classification: Restricted Page 31 • used to test whether the object is an instance of the specified type (class or subclass or interface). class Simple1{ public static void main(String args[]){ Simple1 s=new Simple1(); System.out.println(s instanceof Simple1);//true } } class Animal{} class Dog1 extends Animal{//Dog inherits Animal public static void main(String args[]){ Dog1 d=new Dog1(); System.out.println(d instanceof Animal);//true } }
  • 30. class Dog2{ public static void main(String args[]){ Dog2 d=null; System.out.println(d instanceof Dog2);//false } } Classification: Restricted Page 32 instanceof operator
  • 31. Downcasting Classification: Restricted Page 33 Dog d=new Animal();//Compilation error Dog d=(Dog)new Animal(); //Compiles successfully but ClassCastException could be thrown at runtime