SlideShare a Scribd company logo
1 of 18
1
JavaJava Computer Industry Lab.Computer Industry Lab.
Programming Java
Inheritance
Incheon Paik
2
JavaJava Computer Industry Lab.Computer Industry Lab.
ContentsContents
 Subclasses
 Inheritance & Variables
 Method Overriding
 Inheritance & Methods
 Inheritance & Constructors
 Class Modifier
 Variables Modifier
 Constructor Modifier
 Method Modifier
 The Object and Class Classes
3
JavaJava Computer Industry Lab.Computer Industry Lab.
SubclassesSubclasses
class clsName2 extends clsName1 {
// Body of class
}
Inheritance of a Class
clsName varName;
Declaration of Variable of a
Class
class X {
}
class X1 extends X {
}
class X2 extends X {
}
class X11 extends X1 {
}
class X12 extends X1 {
}
class X21 extends X2 {
}
class X22 extends X2 {
}
class InheritanceHierarchy {
public static void main(String args[]) {
X x;
System.out.println("Instantiating X");
x = new X();
System.out.println("Instantiating X1");
x = new X1();
System.out.println("Instantiating X11");
x = new X11();
System.out.println("Instantiating X12");
x = new X12();
System.out.println("Instantiating X2");
x = new X2();
System.out.println("Instantiating X21");
x = new X21();
System.out.println("Instantiating X22");
x = new X22();
}
}
Instantiating
Inherit
4
JavaJava Computer Industry Lab.Computer Industry Lab.
SubclassesSubclasses
super.varName
Reference to a Subclass
Variable
class W {
float f;
}
class X extends W {
StringBuffer sb;
}
class Y extends X {
String s;
}
class Z extends Y {
Integer i;
}
class Wxyz {
public static void main(String args[]) {
Z z = new Z();
z.f = 4.567f;
z.sb = new StringBuffer("abcde");
z.s = "Teach Yourself Java";
z.i = new Integer(41);
System.out.println("z.f = " + z.f);
System.out.println("z.sb = " + z.sb);
System.out.println("z.s = " + z.s);
System.out.println("z.i = " + z.i);
}
}
Inherited Variables
Inherit
Result :
z.f = 4.567
z.sb = abcde
z.s = Teach Yourself Java
z.i = 41
5
JavaJava Computer Industry Lab.Computer Industry Lab.
SubclassesSubclasses
class E {
int x;
}
class F extends E {
String x;
}
class Ef {
public static void main(String args[]) {
F f = new F();
f.x = "This is a string";
System.out.println("f.x = " + f.x);
E e = new E();
e.x = 45;
System.out.println("e.x = " + e.x);
}
}
class P {
static int x;
}
class Q extends P {
static String x;
}
class Pq {
public static void main(String args[]) {
P p = new P();
p.x = 55;
System.out.println("p.x = " + p.x);
Q q = new Q();
q.x = "This is a string";
System.out.println("q.x = " + q.x);
}
}
Here, if f.x = 30; ?
Result :
p.x = 55
q.x = This is a string
Result :
f.x = This is a string
e.x = 45
6
JavaJava Computer Industry Lab.Computer Industry Lab.
SubclassesSubclasses
class M100 {
int i = 100;
}
class M200 extends M100 {
int i = 200;
void display() {
System.out.println("i = " + i);
System.out.println("super.i = " + super.i);
}
}
class SuperKeyword {
public static void main(String args[]) {
M200 m200 = new M200();
m200.display();
}
}
Result :
i = 200
super.i = 100
7
JavaJava Computer Industry Lab.Computer Industry Lab.
Method OverridingMethod Overriding
Dynamic Method Dispatch Mechanism
Overriding : When the method with same si-
gnature is defined in Subclass
Overloading : Only the same name, but
different in no. or type of parameter
Overloading & Overriding
class A1 {
void hello() {
System.out.println("Hello from A1");
}
}
class B1 extends A1 {
void hello() {
System.out.println("Hello from B1");
}
}
class C1 extends B1 {
void hello() {
System.out.println("Hello from C1");
}
}
class MethodOverriding1 {
public static void main(String args[]) {
C1 obj = new C1();
obj.hello();
}
}
Overrided by hello of B1
Result :
Hello from C1
8
JavaJava Computer Industry Lab.Computer Industry Lab.
Method OverridingMethod Overriding
class A2 {
void hello() {
System.out.println("Hello from A2");
}
}
class B2 extends A2 {
void hello() {
System.out.println("Hello from B2");
}
}
class C2 extends B2 {
void hello() {
System.out.println("Hello from C2");
}
}
class MethodOverriding2 {
public static void main(String args[]) {
A2 obj = new C2();
obj.hello();
}
}
Overrided by hello of B2
Result :
Hello from C2
Object of C2
9
JavaJava Computer Industry Lab.Computer Industry Lab.
InheritInheritanceance and Methodsand Methods
super.mthName(args)
Reference of Methods in
Superclass
class I1 {
void hello(String s) {
System.out.println("I1: " + s);
}
}
class J1 extends I1 {
void hello(String s) {
super.hello(s);
System.out.println("J1: " + s);
}
}
class K1 extends J1 {
void hello(String s) {
super.hello(s);
System.out.println("K1: " + s);
}
}
class SuperForMethods1 {
public static void main(String args[]) {
System.out.println("Instantiating I1");
I1 obj = new I1();
obj.hello("Good morning");
System.out.println("Instantiating J1");
obj = new J1();
obj.hello("Good afternoon");
System.out.println("Instantiating K1");
obj = new K1();
obj.hello("Good evening");
}
}
Result :
Instantiating I1
I1: Good morning
Instantiating J1
I1: Good afternoon
J1: Good afternoon
Instantiating K1
I1: Good evening
J1: Good evening
K1: Good evening
10
JavaJava Computer Industry Lab.Computer Industry Lab.
InheritInheritanceance and Constructorsand Constructors
super (args)
Invoking of Super-Constructor
class S1 {
int s1;
S1() {
System.out.println("S1 Constructor");
s1 = 1;
}
}
class T1 extends S1 {
int t1;
T1() {
System.out.println("T1 Constructor");
t1 = 2;
}
}
class U1 extends T1 {
int u1;
U1() {
System.out.println("U1 Constructor");
u1 = 3;
}
}
class InheritanceAndConstructors1 {
public static void main(String args[]) {
U1 u1 = new U1();
System.out.println("u1.s1 = " + u1.s1);
System.out.println("u1.t1 = " + u1.t1);
System.out.println("u1.u1 = " + u1.u1);
}
}
Result :
S1 Constructor
T1 Constructor
U1 Constructor
u1.s1 = 1
u1.t1 = 2
u1.u1 = 3
this (args)
Invoking Constructor of Same
Class
What does this
mean?
11
JavaJava Computer Industry Lab.Computer Industry Lab.
InheritInheritanceance and Constructorsand Constructors
class S2 {
int s2;
S2(int s2) {
this.s2 = s2;
}
}
class T2 extends S2 {
int t2;
T2(int s2, int t2) {
super(s2);
this.t2 = t2;
}
}
class U2 extends T2 {
int u2;
U2(int s2, int t2, int u2) {
super(s2, t2);
this.u2 = u2;
}
}
class InheritanceAndConstructors2 {
public static void main(String args[]) {
U2 u2 = new U2(1, 2, 3);
System.out.println("u2.s2 = " + u2.s2);
System.out.println("u2.t2 = " + u2.t2);
System.out.println("u2.u2 = " + u2.u2);
}
}
Result :
u2.s2 = 1
u2.t2 = 2
u2.u2 = 3
1) Constructor of Super Class
2) Initializing Field
3) Constructor Body
Invocation Order of Constructor
12
JavaJava Computer Industry Lab.Computer Industry Lab.
ClassClass ModifierModifier
abstract : Can not be instantiated
final : Cannot extend
public : Can be referenced from all
classes.
Qualifier of Class
class Rectangle extends Shape {
void display() {
System.out.println("Rectangle");
}
}
class Triangle extends Shape {
void display() {
System.out.println("Triangle");
}
}
class AbstractClassDemo {
public static void main(String args[]) {
Shape s = new Circle();
s.display();
s = new Rectangle();
s.display();
s = new Triangle();
s.display();
}
}
Result :
Circle
Rectangle
Triangle
abstract class Shape {
void display() {
}
}
class Circle extends Shape {
void display() {
System.out.println("Circle");
}
}
A class which has abstract method(s).
It has not detailed implementation,
and can be implemented in a subclass
Abstract Class
13
JavaJava Computer Industry Lab.Computer Industry Lab.
VariableVariable ModifierModifier
final : a constant
private : can be accessed only in
the same class
protected : can be accessed from
subclass and the same package
public : Can be referenced from all
classes.
static : not instance variable
transient : variable which is not a
part of consistent state of class
volatile : protect of optimization
such as constant propagation.
Variable Modifier
class L {
static final int x = 5;
}
class FinalVariable {
public static void main(String args[]) {
System.out.println(L.x);
}
}
Result :
5
14
JavaJava Computer Industry Lab.Computer Industry Lab.
ConstructorConstructor ModifierModifier
private : can be accessed only in
same class
protected : can be accessed from
subclass and same package
public : Can be referenced from all
classes.
Qualifier of
Constructor
class PrivateConstructor {
public static void main(String args[]) {
// public Constructor Invocation
Person p1 = new Person("John", 30);
System.out.println(p1.name);
System.out.println(p1.age);
// private constructor invoction
// Person p2 = new Person();
}
}
Current Result :
John
30
class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
private Person() {
}
}
What is the result of compilation when we removed
this comment?
15
JavaJava Computer Industry Lab.Computer Industry Lab.
MethodMethod ModifierModifier
abstract : method without implementation
final: cannot override
native : Machine code usage such as C
or C++
private : can be accessed only in the
same class
protected : can be accessed from
subclass and the same package
public : Can be referenced from all
classes.
static : not instance method
synchronized : when executed, lock
among threads
Method Modifier
class DC10 extends JetPlane {
int numEngines() {
return 3;
}
}
class JetPlanes {
public static void main(String args[]) {
System.out.println(new DC8().numEngines());
System.out.println(new DC10().numEngines());
}
}
Result :
4
3
abstract class JetPlane {
abstract int numEngines();
}
class DC8 extends JetPlane {
int numEngines() {
return 4;
}
}
16
JavaJava Computer Industry Lab.Computer Industry Lab.
MethodMethod ModifierModifier
Result :
Equal
class Singleton {
static Singleton singleton;
private Singleton() {
}
public static Singleton getInstance() {
if (singleton == null)
singleton = new Singleton();
return singleton;
}
}
class SingletonDemo {
public static void main(String args[]) {
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
if (s1 == s2)
System.out.println("Equal");
else
System.out.println("Not equal");
}
}
17
JavaJava Computer Industry Lab.Computer Industry Lab.
The Object & Class ClassesThe Object & Class Classes
boolean equals(Object obj)
equals() method
Object Class : Most
Top class in Java
Class getClass()
getClass() method
String toString()
toString() method
String getName()
getName() method
Class getSuperClass()
getSuperClass()
method
Static Class forName (String
cIsName) throws
ClassNotFoundException
forName() method
Class Class
18
JavaJava Computer Industry Lab.Computer Industry Lab.
The Object & ClassThe Object & Class
ClassesClasses
Result :
Class java.lang.Integer
class ClassDemo {
public static void main(String args[]) {
Integer obj = new Integer(8);
Class cls = obj.getClass();
System.out.println(cls);
}
}

More Related Content

What's hot

Interface
InterfaceInterface
Interfacevvpadhu
 
11slide
11slide11slide
11slideIIUM
 
Java Programs Lab File
Java Programs Lab FileJava Programs Lab File
Java Programs Lab FileKandarp Tiwari
 
Operators
OperatorsOperators
Operatorsvvpadhu
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queuesIntro C# Book
 
Fnt software solutions placement paper
Fnt software solutions placement paperFnt software solutions placement paper
Fnt software solutions placement paperfntsofttech
 
How Data Flow analysis works in a static code analyzer
How Data Flow analysis works in a static code analyzerHow Data Flow analysis works in a static code analyzer
How Data Flow analysis works in a static code analyzerAndrey Karpov
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handlingIntro C# Book
 
Execution flow of main() method inside jvm
Execution flow of main() method inside jvmExecution flow of main() method inside jvm
Execution flow of main() method inside jvmsaurav uniyal
 
PVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error ExamplesPVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error ExamplesAndrey Karpov
 
Java language fundamentals
Java language fundamentalsJava language fundamentals
Java language fundamentalsKapish Joshi
 
Design pattern - part 1
Design pattern - part 1Design pattern - part 1
Design pattern - part 1Jieyi Wu
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstractionIntro C# Book
 
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...Udayan Khattry
 

What's hot (20)

Java Threads
Java ThreadsJava Threads
Java Threads
 
Interface
InterfaceInterface
Interface
 
11slide
11slide11slide
11slide
 
Java Programs Lab File
Java Programs Lab FileJava Programs Lab File
Java Programs Lab File
 
Operators
OperatorsOperators
Operators
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queues
 
Fnt software solutions placement paper
Fnt software solutions placement paperFnt software solutions placement paper
Fnt software solutions placement paper
 
How Data Flow analysis works in a static code analyzer
How Data Flow analysis works in a static code analyzerHow Data Flow analysis works in a static code analyzer
How Data Flow analysis works in a static code analyzer
 
Java programs
Java programsJava programs
Java programs
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
 
Class method
Class methodClass method
Class method
 
Execution flow of main() method inside jvm
Execution flow of main() method inside jvmExecution flow of main() method inside jvm
Execution flow of main() method inside jvm
 
PVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error ExamplesPVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error Examples
 
Java language fundamentals
Java language fundamentalsJava language fundamentals
Java language fundamentals
 
Loop
LoopLoop
Loop
 
Java Inheritance
Java InheritanceJava Inheritance
Java Inheritance
 
Chapter 2 Java Methods
Chapter 2 Java MethodsChapter 2 Java Methods
Chapter 2 Java Methods
 
Design pattern - part 1
Design pattern - part 1Design pattern - part 1
Design pattern - part 1
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...
 

Similar to Inheritance and-polymorphism

Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsMuhammadTalha436
 
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...Ayes Chinmay
 
Core java pract_sem iii
Core java pract_sem iiiCore java pract_sem iii
Core java pract_sem iiiNiraj Bharambe
 
Assignment 7
Assignment 7Assignment 7
Assignment 7IIUM
 
Java practice programs for beginners
Java practice programs for beginnersJava practice programs for beginners
Java practice programs for beginnersishan0019
 
Java programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarJava programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarROHIT JAISWAR
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and UtilitiesPramod Kumar
 
OOP with Java - continued
OOP with Java - continuedOOP with Java - continued
OOP with Java - continuedRatnaJava
 
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloading
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloadingRiga DevDays 2017 - The hitchhiker’s guide to Java class reloading
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloadingAnton Arhipov
 

Similar to Inheritance and-polymorphism (20)

Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ Exams
 
Inheritance.pptx
Inheritance.pptxInheritance.pptx
Inheritance.pptx
 
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
 
Core java pract_sem iii
Core java pract_sem iiiCore java pract_sem iii
Core java pract_sem iii
 
00_Introduction to Java.ppt
00_Introduction to Java.ppt00_Introduction to Java.ppt
00_Introduction to Java.ppt
 
sample_midterm.pdf
sample_midterm.pdfsample_midterm.pdf
sample_midterm.pdf
 
11slide.ppt
11slide.ppt11slide.ppt
11slide.ppt
 
Assignment 7
Assignment 7Assignment 7
Assignment 7
 
7 inheritance
7 inheritance7 inheritance
7 inheritance
 
OOP Lab Report.docx
OOP Lab Report.docxOOP Lab Report.docx
OOP Lab Report.docx
 
Java practical
Java practicalJava practical
Java practical
 
JAVAPGMS.docx
JAVAPGMS.docxJAVAPGMS.docx
JAVAPGMS.docx
 
Java practice programs for beginners
Java practice programs for beginnersJava practice programs for beginners
Java practice programs for beginners
 
Java programs
Java programsJava programs
Java programs
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
Computer programming 2 Lesson 15
Computer programming 2  Lesson 15Computer programming 2  Lesson 15
Computer programming 2 Lesson 15
 
Java programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarJava programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswar
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and Utilities
 
OOP with Java - continued
OOP with Java - continuedOOP with Java - continued
OOP with Java - continued
 
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloading
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloadingRiga DevDays 2017 - The hitchhiker’s guide to Java class reloading
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloading
 

Recently uploaded

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
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
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
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
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
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 

Recently uploaded (20)

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
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
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...
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
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
 
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
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 

Inheritance and-polymorphism

  • 1. 1 JavaJava Computer Industry Lab.Computer Industry Lab. Programming Java Inheritance Incheon Paik
  • 2. 2 JavaJava Computer Industry Lab.Computer Industry Lab. ContentsContents  Subclasses  Inheritance & Variables  Method Overriding  Inheritance & Methods  Inheritance & Constructors  Class Modifier  Variables Modifier  Constructor Modifier  Method Modifier  The Object and Class Classes
  • 3. 3 JavaJava Computer Industry Lab.Computer Industry Lab. SubclassesSubclasses class clsName2 extends clsName1 { // Body of class } Inheritance of a Class clsName varName; Declaration of Variable of a Class class X { } class X1 extends X { } class X2 extends X { } class X11 extends X1 { } class X12 extends X1 { } class X21 extends X2 { } class X22 extends X2 { } class InheritanceHierarchy { public static void main(String args[]) { X x; System.out.println("Instantiating X"); x = new X(); System.out.println("Instantiating X1"); x = new X1(); System.out.println("Instantiating X11"); x = new X11(); System.out.println("Instantiating X12"); x = new X12(); System.out.println("Instantiating X2"); x = new X2(); System.out.println("Instantiating X21"); x = new X21(); System.out.println("Instantiating X22"); x = new X22(); } } Instantiating Inherit
  • 4. 4 JavaJava Computer Industry Lab.Computer Industry Lab. SubclassesSubclasses super.varName Reference to a Subclass Variable class W { float f; } class X extends W { StringBuffer sb; } class Y extends X { String s; } class Z extends Y { Integer i; } class Wxyz { public static void main(String args[]) { Z z = new Z(); z.f = 4.567f; z.sb = new StringBuffer("abcde"); z.s = "Teach Yourself Java"; z.i = new Integer(41); System.out.println("z.f = " + z.f); System.out.println("z.sb = " + z.sb); System.out.println("z.s = " + z.s); System.out.println("z.i = " + z.i); } } Inherited Variables Inherit Result : z.f = 4.567 z.sb = abcde z.s = Teach Yourself Java z.i = 41
  • 5. 5 JavaJava Computer Industry Lab.Computer Industry Lab. SubclassesSubclasses class E { int x; } class F extends E { String x; } class Ef { public static void main(String args[]) { F f = new F(); f.x = "This is a string"; System.out.println("f.x = " + f.x); E e = new E(); e.x = 45; System.out.println("e.x = " + e.x); } } class P { static int x; } class Q extends P { static String x; } class Pq { public static void main(String args[]) { P p = new P(); p.x = 55; System.out.println("p.x = " + p.x); Q q = new Q(); q.x = "This is a string"; System.out.println("q.x = " + q.x); } } Here, if f.x = 30; ? Result : p.x = 55 q.x = This is a string Result : f.x = This is a string e.x = 45
  • 6. 6 JavaJava Computer Industry Lab.Computer Industry Lab. SubclassesSubclasses class M100 { int i = 100; } class M200 extends M100 { int i = 200; void display() { System.out.println("i = " + i); System.out.println("super.i = " + super.i); } } class SuperKeyword { public static void main(String args[]) { M200 m200 = new M200(); m200.display(); } } Result : i = 200 super.i = 100
  • 7. 7 JavaJava Computer Industry Lab.Computer Industry Lab. Method OverridingMethod Overriding Dynamic Method Dispatch Mechanism Overriding : When the method with same si- gnature is defined in Subclass Overloading : Only the same name, but different in no. or type of parameter Overloading & Overriding class A1 { void hello() { System.out.println("Hello from A1"); } } class B1 extends A1 { void hello() { System.out.println("Hello from B1"); } } class C1 extends B1 { void hello() { System.out.println("Hello from C1"); } } class MethodOverriding1 { public static void main(String args[]) { C1 obj = new C1(); obj.hello(); } } Overrided by hello of B1 Result : Hello from C1
  • 8. 8 JavaJava Computer Industry Lab.Computer Industry Lab. Method OverridingMethod Overriding class A2 { void hello() { System.out.println("Hello from A2"); } } class B2 extends A2 { void hello() { System.out.println("Hello from B2"); } } class C2 extends B2 { void hello() { System.out.println("Hello from C2"); } } class MethodOverriding2 { public static void main(String args[]) { A2 obj = new C2(); obj.hello(); } } Overrided by hello of B2 Result : Hello from C2 Object of C2
  • 9. 9 JavaJava Computer Industry Lab.Computer Industry Lab. InheritInheritanceance and Methodsand Methods super.mthName(args) Reference of Methods in Superclass class I1 { void hello(String s) { System.out.println("I1: " + s); } } class J1 extends I1 { void hello(String s) { super.hello(s); System.out.println("J1: " + s); } } class K1 extends J1 { void hello(String s) { super.hello(s); System.out.println("K1: " + s); } } class SuperForMethods1 { public static void main(String args[]) { System.out.println("Instantiating I1"); I1 obj = new I1(); obj.hello("Good morning"); System.out.println("Instantiating J1"); obj = new J1(); obj.hello("Good afternoon"); System.out.println("Instantiating K1"); obj = new K1(); obj.hello("Good evening"); } } Result : Instantiating I1 I1: Good morning Instantiating J1 I1: Good afternoon J1: Good afternoon Instantiating K1 I1: Good evening J1: Good evening K1: Good evening
  • 10. 10 JavaJava Computer Industry Lab.Computer Industry Lab. InheritInheritanceance and Constructorsand Constructors super (args) Invoking of Super-Constructor class S1 { int s1; S1() { System.out.println("S1 Constructor"); s1 = 1; } } class T1 extends S1 { int t1; T1() { System.out.println("T1 Constructor"); t1 = 2; } } class U1 extends T1 { int u1; U1() { System.out.println("U1 Constructor"); u1 = 3; } } class InheritanceAndConstructors1 { public static void main(String args[]) { U1 u1 = new U1(); System.out.println("u1.s1 = " + u1.s1); System.out.println("u1.t1 = " + u1.t1); System.out.println("u1.u1 = " + u1.u1); } } Result : S1 Constructor T1 Constructor U1 Constructor u1.s1 = 1 u1.t1 = 2 u1.u1 = 3 this (args) Invoking Constructor of Same Class What does this mean?
  • 11. 11 JavaJava Computer Industry Lab.Computer Industry Lab. InheritInheritanceance and Constructorsand Constructors class S2 { int s2; S2(int s2) { this.s2 = s2; } } class T2 extends S2 { int t2; T2(int s2, int t2) { super(s2); this.t2 = t2; } } class U2 extends T2 { int u2; U2(int s2, int t2, int u2) { super(s2, t2); this.u2 = u2; } } class InheritanceAndConstructors2 { public static void main(String args[]) { U2 u2 = new U2(1, 2, 3); System.out.println("u2.s2 = " + u2.s2); System.out.println("u2.t2 = " + u2.t2); System.out.println("u2.u2 = " + u2.u2); } } Result : u2.s2 = 1 u2.t2 = 2 u2.u2 = 3 1) Constructor of Super Class 2) Initializing Field 3) Constructor Body Invocation Order of Constructor
  • 12. 12 JavaJava Computer Industry Lab.Computer Industry Lab. ClassClass ModifierModifier abstract : Can not be instantiated final : Cannot extend public : Can be referenced from all classes. Qualifier of Class class Rectangle extends Shape { void display() { System.out.println("Rectangle"); } } class Triangle extends Shape { void display() { System.out.println("Triangle"); } } class AbstractClassDemo { public static void main(String args[]) { Shape s = new Circle(); s.display(); s = new Rectangle(); s.display(); s = new Triangle(); s.display(); } } Result : Circle Rectangle Triangle abstract class Shape { void display() { } } class Circle extends Shape { void display() { System.out.println("Circle"); } } A class which has abstract method(s). It has not detailed implementation, and can be implemented in a subclass Abstract Class
  • 13. 13 JavaJava Computer Industry Lab.Computer Industry Lab. VariableVariable ModifierModifier final : a constant private : can be accessed only in the same class protected : can be accessed from subclass and the same package public : Can be referenced from all classes. static : not instance variable transient : variable which is not a part of consistent state of class volatile : protect of optimization such as constant propagation. Variable Modifier class L { static final int x = 5; } class FinalVariable { public static void main(String args[]) { System.out.println(L.x); } } Result : 5
  • 14. 14 JavaJava Computer Industry Lab.Computer Industry Lab. ConstructorConstructor ModifierModifier private : can be accessed only in same class protected : can be accessed from subclass and same package public : Can be referenced from all classes. Qualifier of Constructor class PrivateConstructor { public static void main(String args[]) { // public Constructor Invocation Person p1 = new Person("John", 30); System.out.println(p1.name); System.out.println(p1.age); // private constructor invoction // Person p2 = new Person(); } } Current Result : John 30 class Person { String name; int age; public Person(String name, int age) { this.name = name; this.age = age; } private Person() { } } What is the result of compilation when we removed this comment?
  • 15. 15 JavaJava Computer Industry Lab.Computer Industry Lab. MethodMethod ModifierModifier abstract : method without implementation final: cannot override native : Machine code usage such as C or C++ private : can be accessed only in the same class protected : can be accessed from subclass and the same package public : Can be referenced from all classes. static : not instance method synchronized : when executed, lock among threads Method Modifier class DC10 extends JetPlane { int numEngines() { return 3; } } class JetPlanes { public static void main(String args[]) { System.out.println(new DC8().numEngines()); System.out.println(new DC10().numEngines()); } } Result : 4 3 abstract class JetPlane { abstract int numEngines(); } class DC8 extends JetPlane { int numEngines() { return 4; } }
  • 16. 16 JavaJava Computer Industry Lab.Computer Industry Lab. MethodMethod ModifierModifier Result : Equal class Singleton { static Singleton singleton; private Singleton() { } public static Singleton getInstance() { if (singleton == null) singleton = new Singleton(); return singleton; } } class SingletonDemo { public static void main(String args[]) { Singleton s1 = Singleton.getInstance(); Singleton s2 = Singleton.getInstance(); if (s1 == s2) System.out.println("Equal"); else System.out.println("Not equal"); } }
  • 17. 17 JavaJava Computer Industry Lab.Computer Industry Lab. The Object & Class ClassesThe Object & Class Classes boolean equals(Object obj) equals() method Object Class : Most Top class in Java Class getClass() getClass() method String toString() toString() method String getName() getName() method Class getSuperClass() getSuperClass() method Static Class forName (String cIsName) throws ClassNotFoundException forName() method Class Class
  • 18. 18 JavaJava Computer Industry Lab.Computer Industry Lab. The Object & ClassThe Object & Class ClassesClasses Result : Class java.lang.Integer class ClassDemo { public static void main(String args[]) { Integer obj = new Integer(8); Class cls = obj.getClass(); System.out.println(cls); } }