SlideShare una empresa de Scribd logo
1 de 38
Polymorphism
• Polymorphism is the ability of an object to take on
many forms.
• The most common use of polymorphism in OOP
occurs when a parent class reference is used to
refer to a child class object.
• Any Java object that can pass more than one IS-A
test is considered to be polymorphic.
• In Java, all Java objects are polymorphic since any
object will pass the IS-A test for their own type and
for the class Object.
Polymorphism
• It is important to know that the only possible way to
access an object is through a reference variable.
• A reference variable can be of only one type.
• Once declared, the type of a reference variable
cannot be changed.
• The reference variable can be reassigned to other
objects provided that it is not declared final.
• The type of the reference variable would determine
the methods that it can invoke on the object.
Polymorphism
• A reference variable can refer to any object of its
declared type or any subtype of its declared type.
• A reference variable can be declared as a class or
interface type.
refer example from next slide.
Polymorphism
Method Overriding Cont..
1. Sub class can override the methods defined by the super
class.
2. Overridden Methods in the sub classes should have same
name, same signature , same return type and may have
either the same or higher scope than super class method.
3. Java implements Run Time Polymorphism/ Dynamic Method
Dispatch by Method Overriding. [Late Binding]
4. Call to Overridden Methods is Resolved at Run Time.
5. Call to a overridden method is not decided by the type of
reference variable Rather by the type of the object where
reference variable is pointing.
6. While Overriding a Method, the sub class should assign
either same or higher access level than super class method.
EXAMPLE METHOD OVERRIDING
class A
{
void show()
{
System.out.println("Hello This is show() in A");
}// End of show() Method
B class overrides show() method from
} // End of class A
super class A
class B extends A
{
void show()
{
System.out.println("Hello This is show() in B");
}// End of show() Method
} // End of class B class override
{
public static void main(String args[])
Call to show()
{
of A class
// super class reference variable
// can point to sub class object
A a1 = new A();
a1.show();
Call to show()
a1 = new B();
of B class
a1.show();
}
Is this Method

class A
Overriding
{
void show(int a)
NO
{
System.out.println("Hello This is show()
in A");
}
}
class B extends A
{
void show()
{
System.out.println("Hello This is show()
in B");
}
}
OUTPUT
Hello This is show() in A
Hello This is show() in A
Hello This is show() in B

class override1
{
public static void main(String args[])
{
/*
A a1 = new B();
a1.show(); */
A a1 = new A();
a1.show(10);
B b1 = new B();
b1.show(10);
b1.show(); }
Dynamic Method Dispatch
1. Super class reference variable can refer to a sub class object.
2. Super class variable if refers to sub class object can call only
overridden methods.

3. Call to an overridden method is decided by the type of object
referred to.
A a1 = new B();
a1.show(); // call to show() of B
a1 = new C();
a1.show(); // call to show() of C
a1 = new D();
a1.show(); // call to show() of D

A

B

C

Assume show() Method is
Overridden by sub classes

D
DYNAMIC METHOD DISPATCH
class A
{
void show()
{
System.out.println("Hello This is
show() in A");
}
}
class B extends A
{
void show()
{
System.out.println("Hello This is
show() in B");
}
}

class C extends A
{
void show()
{
System.out.println("Hello This
is show() in C");
}
}
class D extends A
{
void show()
{
System.out.println("Hello This
is show() in D");
}
}
CONTINUED…..
class override2
{
public static void main(String
args[])
{
Hello This is show() in A
A a1 = new A();
Hello This is show() in B
a1.show();
a1 = new B();
Hello This is show() in C
a1.show();
Hello This is show() in D
a1 = new C();
a1.show();
a1 = new D();
a1.show();
}
}
Method Overriding Cont..
1. Sub class can override the methods defined by the super
class.
2. Overridden Methods in the sub classes should have same
name, same signature , same return type and may have
either the same or higher scope than super class method.
3. Java implements Run Time Polymorphism/ Dynamic Method
Dispatch by Method Overriding. [Late Binding]
4. Call to Overridden Methods is Resolved at Run Time.
5. Call to a overridden method is not decided by the type of
reference variable Rather by the type of the object where
reference variable is pointing.
6. While Overriding a Method, the sub class should assign
either same or higher access level than super class method.
class override3
{
public static void main(String args[])
{
A a1 = new B();
B b1 = (B) a1;
/*
A a1 = new B();
C c1 = (C) a1;
Exception in thread "main"
java.lang.ClassCastException: B
at override3.main(override3.java:39)
*/
}
}
Examples Overriding
class A
{
void show() { …. }
}
class B extends A
{
void show() { …. }
void show(int x) { … }
void print() { … }
}

A a1 = new B();
a1.show() ;
// Valid
// a1.show(10); // Invalid
//a1.print();
// Invalid

When a super class variable points to a sub class
object, then it can only call overridden methods of the sub
class.
class A
{
protected void show()
{
System.out.println("Hi");
}
}
class B extends A
{
void show()
{
System.out.println("Hi");
}
}

D:Java1>javac AB.java
AB.java:10: show() in B cannot
override show() in A; attempting
to assign weaker
access privileges; was protected
void show()
^
1 error
class A
{
private void show()
{
System.out.println("Hi");
}
}
class B extends A
{
int show()
{
System.out.println("Hi");
return 10;
}
}

IS THIS METHOD
OVERRIDING

NO
CODE WILL COMPILE
& RUN SUCESSFULLY
class A
{
static int show()
{
System.out.println("class A");
return 0;
}
}
class B extends A
{
void show()
{
System.out.println("class B");
}
}

What’s Wrong Here

sample.java:12: show() in B
cannot override show() in A;
overridden method is static
void show()
^
1 error
Nested Classes

Java programming language allows you to
define a class within another class
Enclosing
class OuterClass
Class OR
{ ...
Outer Class
A nested class is a member
class NestedClass { ... of its enclosing class
}

}

Nested
Class
1.Nested has access to other members of the
enclosing class,even if they are declared private
2. Can be private, public, protected or friendly
access
Nested Class Types
Static nested classes
1. Static keyword applied for class declaration
2. Static nested class can use the instance
fields/methods of the outer class only through object
reference.
3. Static nested class can be accessed

OuterClass.StaticNestedClass
4. To create an object for the static nested class, use this
syntax:
OuterClass.StaticNestedClass nestedObject = new
OuterClass.StaticNestedClass();
Nested Class Types cont..
•

Non-Static nested classes

1. These nested classes do not have static keyword applied
2. Non-Static nested class can use the instance fields/methods of
the outer class directly.
3. To create an object for the non-static nested class, use this
syntax:

OuterClass.NestedClass nestedObject = Outerobjectreference.
new innerclass();
Inner class instance can
only exists inside
Outer class instance.
Example 1 [Non-static Nested Class]
class B
class A
{
{
int b;
private int a; Outer Class
Nested
B(int b)
A(int a)
class with
{
{
friendly
int c = b+10; access
this.a =a;
this.b = c;
}
}
void print()
void show()
{
{
System.out.println("a="+a)
print();
;
System.out.println("b="+b);
}
Call to
}
print() of
} // End of class B
outer class
} // End of class A
Example 1 [Non-static Nested Class]
class innertest1
{
public static void main(String args[])
{
A a1 = new A(10);
A.B b1 = a1.new B(100);
b1.show();
}
}

cont….

Inner class Name

Outer class Reference

To create an inner class instance for nonstatic classes you need an outer class
reference.
Inner class Reference
Outer class Name

If class B is Private then it is not visible in main().
A.B b1 = a1.new B(100); is WRONG/INVALID
Example 2
class A
{
private int a;
private int b=10;
A(int a)
{
this.a=a;
}

Local b
B’s instance Field b
A’s instance Field b
void show()
{
B b1 = new B(30);
b1.show();
}
} // End of Outer class A

Outer class
Nested Inner class [Nonstatic Type]

class B
{
private int b;
Instance Field of B
B(int b)
{
this.b =b;
}
Outer Class A’s a
void show()
{
int b=20;
System.out.println("a="+a);
System.out.println("b="+b);
System.out.println("this.b="+this.b);
System.out.println("Outer b="+A.this.b);
}
} // End of B inner class
class innerTest
{
public static void main(String args[])
{
// Create an inner class B's instance
// Call show() method
// STEP 1
// Create an Outer Instance first

A a1 = new A(20);
A.B b1 = a1.new B(-30);
b1.show();

a=20
b=20
this.b=-30
Outer b=10

// inner class object instantiation thru anonymous
outer
// reference
A.B b2 = new A(30).new B(-40);
a=30
b2.show();
b=20
}
this.b=-40
}
Outer b=10
Static Inner class / Static Nested class Example
class A
{
private int a;
A(int a)
{
this.a =a;
}
void print()
{
System.out.println("a="+a
);
}
Static nested class can
refere to outer members
only through outer
reference

static class B
{
int b;
B(int b)
Static inner
{
class
int c = b+10;
this.b = c;
}
void show()
{
// print(); INVALID
A a1 = new A(10);
a1.print();
System.out.println("b="+b);
}
} // End of class B
} // End of class A
Example cont….

class innertest10
{
public static void main(String args[])
{
A.B b1 = new A.B(100);
b1.show();
Instance of static Inner
}
class
}
Static Nested class Example 2
class A
{
private int a;
protected static int b=10;
A(int a)
{
this.a=a;
}
public void show()
{
System.out.println("a="+a);
display();
}
public static void display()
{
System.out.println("b="+b);
}
Example 2 cont….
static class B
{
private int a;
protected static int b=100;
B(int a)
{
this.a=a;
}
void show()
{
// A.this.show(); // Won't work show() is non-static in outer
display(); // Will work as method is static in outer
System.out.println("a="+a);
// System.out.println("a="+A.this.a);
// Won't work a is non-static in outer
System.out.println("b="+b); // Will refer to its own b
System.out.println("A'sb="+A.b); // will refer to outer class B
new A(40).show();
// This is how you can call non static methods of outer
}
} // End of inner class B
} // End of class A
Example 2 cont….
class innerTest1
{
public static void main(String
args[])
{
A.B b1 = new A.B(-30);
D:jdk1.3bin>java innerTest1
b1.show();
}
b=10
}
a=-30
b=100
A'sb=10
a=40
b=10
Local Inner classes [ Classes Within method body]

class A
{
private int a;
protected static int b=10;
A(int a)
{
this.a=a;
1.
}
void show()
2.
{
class B
{}
3.
}
}
4.

Class declared within a
method body.
Here method is show()
Local inner classes Can not
be declared as
public,private or protected

Class B is visible only in method
show().
It can be used within this show()
method only
Local inner classes can only use final
variables from its enclosing method.
However inner classes can refer to its
fields of enclosing class.
class A
{
private int a;
protected static int b=10;
A(int a)
{
this.a=a;
}
void show()
{
int x=10;
class B
{
private int b;
B(int b)
{
this.b=b;
}
void display()
{

System.out.println("a="+a);
System.out.println("b="+b);
System.out.println("x="+x);
}

} // End of class B
} // End of show() method
} // End of A class

D:jdk1.3bin>javac
innerTest2.java
innerTest2.java:23: local
variable x is accessed from
within inner class;
to be declared final
System.out.println("x="+x);
^
1 error

Reference for A’s a
Reference for B’s b
Reference is wrong / errorneous
‘x’ is local variable inside the local
method. Local classes can use only
final fields from enclosing method
class innertest
{
public static void
main(String args[])
{
final int a1=10;
new A(20).show();
print();
}// End of main
static void print()
{

/*
A a1 = new A(30);
a1.show();
*/

System.out.println("Hello"
);
}
}

class A
{
private int a;
private int b;
int c;
A(int a)
{
this.a =a;
b = a+20;
c = a+40;
}
void show()
{
System.out.println("a1="+a1);
System.out.println("a="+a);
System.out.println("b="+b);
System.out.println("c="+c);
}
} //End of A
OUTPUT

E:oop>java innertest
a1=10
a=20
b=40
c=60
Hello
Anonymous Inner classes
• Another category of local inner classes
• Classes without any name i.e classes having
no name
• Can either implements an interface or
extends a class.
• Can not have more than one instance active
at a time.
• Whole body of the class is declared in a single
statement ending with ;
Cont…
• Syntax [ If extending a class]
[variable_type_superclass =] new superclass_name() {
// properties and methods
} [;]
• Syntax [ If implementing an interface]
[variable_type_reference =] new reference_name() {
// properties and methods
} [;]
Anonymous Inner Class Example
class A
{
private int a;
A(int a)
{
this.a =a;
}
void show()
{
System.out.println("a="+a);
} // End of show()
}// End of class A
class innertest1
{
public static void main(String args[])
{

Anonymous inner class extending super class A

A a1 = new A(20){
public void show()
{
super.show();
System.out.println("Hello");
}
public void display()
{
System.out.println("Hi");
}
};
a1.show();
// a1.display();
Calling show from inner class
}
}
interface X
{
int sum(int a,int b);
int mul(int x,int y);
}
class innertest2
{
public static void main(String args[])
{
Anonymous inner class implementing an interface

X x1 = new X()
{
public int sum(int a,int b)
{
return a+b;
}
public int mul(int a,int b)
{
return a*b;
}
};
System.out.println(x1.sum(10,20));
System.out.println(x1.mul(10,20));
}// End of main
}// End of innertest2

Más contenido relacionado

La actualidad más candente

Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#Abid Kohistani
 
Object oriented programming in php 5
Object oriented programming in php 5Object oriented programming in php 5
Object oriented programming in php 5Sayed Ahmed
 
Friend functions
Friend functions Friend functions
Friend functions Megha Singh
 
class and objects
class and objectsclass and objects
class and objectsPayel Guria
 
Interfaces and abstract classes
Interfaces and abstract classesInterfaces and abstract classes
Interfaces and abstract classesAKANSH SINGHAL
 
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
 
Binding,interface,abstarct class
Binding,interface,abstarct classBinding,interface,abstarct class
Binding,interface,abstarct classvishal choudhary
 
Esoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsEsoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsRasan Samarasinghe
 
DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#Rasan Samarasinghe
 
Templates and Exception Handling in C++
Templates and Exception Handling in C++Templates and Exception Handling in C++
Templates and Exception Handling in C++Nimrita Koul
 
Chapter 4:Object-Oriented Basic Concepts
Chapter 4:Object-Oriented Basic ConceptsChapter 4:Object-Oriented Basic Concepts
Chapter 4:Object-Oriented Basic ConceptsIt Academy
 
Abstract class in c++
Abstract class in c++Abstract class in c++
Abstract class in c++Sujan Mia
 
Abstract & Interface
Abstract & InterfaceAbstract & Interface
Abstract & InterfaceLinh Lê
 
Diving in OOP (Day 2): Polymorphism and Inheritance (Inheritance)
Diving in OOP (Day 2): Polymorphism and Inheritance (Inheritance)Diving in OOP (Day 2): Polymorphism and Inheritance (Inheritance)
Diving in OOP (Day 2): Polymorphism and Inheritance (Inheritance)Akhil Mittal
 

La actualidad más candente (18)

Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#
 
Object oriented programming in php 5
Object oriented programming in php 5Object oriented programming in php 5
Object oriented programming in php 5
 
Friend functions
Friend functions Friend functions
Friend functions
 
class and objects
class and objectsclass and objects
class and objects
 
Interfaces and abstract classes
Interfaces and abstract classesInterfaces and abstract classes
Interfaces and abstract classes
 
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...
 
Inheritance
InheritanceInheritance
Inheritance
 
Binding,interface,abstarct class
Binding,interface,abstarct classBinding,interface,abstarct class
Binding,interface,abstarct class
 
Esoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsEsoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basics
 
Test Presentation
Test PresentationTest Presentation
Test Presentation
 
DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#
 
C++ polymorphism
C++ polymorphismC++ polymorphism
C++ polymorphism
 
Templates and Exception Handling in C++
Templates and Exception Handling in C++Templates and Exception Handling in C++
Templates and Exception Handling in C++
 
Chapter 4:Object-Oriented Basic Concepts
Chapter 4:Object-Oriented Basic ConceptsChapter 4:Object-Oriented Basic Concepts
Chapter 4:Object-Oriented Basic Concepts
 
Abstract class in c++
Abstract class in c++Abstract class in c++
Abstract class in c++
 
Abstract & Interface
Abstract & InterfaceAbstract & Interface
Abstract & Interface
 
Java Programming
Java Programming Java Programming
Java Programming
 
Diving in OOP (Day 2): Polymorphism and Inheritance (Inheritance)
Diving in OOP (Day 2): Polymorphism and Inheritance (Inheritance)Diving in OOP (Day 2): Polymorphism and Inheritance (Inheritance)
Diving in OOP (Day 2): Polymorphism and Inheritance (Inheritance)
 

Similar a Java tutorial part 2

Similar a Java tutorial part 2 (20)

Lecture 14 (inheritance basics)
Lecture 14 (inheritance basics)Lecture 14 (inheritance basics)
Lecture 14 (inheritance basics)
 
Learn Java Part 11
Learn Java Part 11Learn Java Part 11
Learn Java Part 11
 
Learn Java Part 11
Learn Java Part 11Learn Java Part 11
Learn Java Part 11
 
Java
JavaJava
Java
 
Inheritance chepter 7
Inheritance chepter 7Inheritance chepter 7
Inheritance chepter 7
 
Keyword of java
Keyword of javaKeyword of java
Keyword of java
 
Object Oriented Programming in PHP
Object Oriented Programming  in PHPObject Oriented Programming  in PHP
Object Oriented Programming in PHP
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Core java day5
Core java day5Core java day5
Core java day5
 
Inheritance Slides
Inheritance SlidesInheritance Slides
Inheritance Slides
 
Inheritance and Interfaces
Inheritance and InterfacesInheritance and Interfaces
Inheritance and Interfaces
 
‫Chapter3 inheritance
‫Chapter3 inheritance‫Chapter3 inheritance
‫Chapter3 inheritance
 
Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10
 
Static binding
Static bindingStatic binding
Static binding
 
Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry Level
 
Chap11
Chap11Chap11
Chap11
 
Inheritance
InheritanceInheritance
Inheritance
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
 
Java unit2
Java unit2Java unit2
Java unit2
 

Más de Mumbai Academisc (20)

Non ieee java projects list
Non  ieee java projects list Non  ieee java projects list
Non ieee java projects list
 
Non ieee dot net projects list
Non  ieee dot net projects list Non  ieee dot net projects list
Non ieee dot net projects list
 
Ieee java projects list
Ieee java projects list Ieee java projects list
Ieee java projects list
 
Ieee 2014 java projects list
Ieee 2014 java projects list Ieee 2014 java projects list
Ieee 2014 java projects list
 
Ieee 2014 dot net projects list
Ieee 2014 dot net projects list Ieee 2014 dot net projects list
Ieee 2014 dot net projects list
 
Ieee 2013 java projects list
Ieee 2013 java projects list Ieee 2013 java projects list
Ieee 2013 java projects list
 
Ieee 2013 dot net projects list
Ieee 2013 dot net projects listIeee 2013 dot net projects list
Ieee 2013 dot net projects list
 
Ieee 2012 dot net projects list
Ieee 2012 dot net projects listIeee 2012 dot net projects list
Ieee 2012 dot net projects list
 
Spring ppt
Spring pptSpring ppt
Spring ppt
 
Ejb notes
Ejb notesEjb notes
Ejb notes
 
Java web programming
Java web programmingJava web programming
Java web programming
 
Java programming-examples
Java programming-examplesJava programming-examples
Java programming-examples
 
Hibernate tutorial
Hibernate tutorialHibernate tutorial
Hibernate tutorial
 
J2ee project lists:-Mumbai Academics
J2ee project lists:-Mumbai AcademicsJ2ee project lists:-Mumbai Academics
J2ee project lists:-Mumbai Academics
 
Web based development
Web based developmentWeb based development
Web based development
 
Jdbc
JdbcJdbc
Jdbc
 
Java tutorial part 4
Java tutorial part 4Java tutorial part 4
Java tutorial part 4
 
Java tutorial part 3
Java tutorial part 3Java tutorial part 3
Java tutorial part 3
 
Engineering
EngineeringEngineering
Engineering
 
Jsp
JspJsp
Jsp
 

Último

"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
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
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
"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
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
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
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 

Último (20)

"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
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
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
"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
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
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
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
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
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 

Java tutorial part 2

  • 1. Polymorphism • Polymorphism is the ability of an object to take on many forms. • The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. • Any Java object that can pass more than one IS-A test is considered to be polymorphic. • In Java, all Java objects are polymorphic since any object will pass the IS-A test for their own type and for the class Object.
  • 2. Polymorphism • It is important to know that the only possible way to access an object is through a reference variable. • A reference variable can be of only one type. • Once declared, the type of a reference variable cannot be changed. • The reference variable can be reassigned to other objects provided that it is not declared final. • The type of the reference variable would determine the methods that it can invoke on the object.
  • 3. Polymorphism • A reference variable can refer to any object of its declared type or any subtype of its declared type. • A reference variable can be declared as a class or interface type. refer example from next slide.
  • 5. Method Overriding Cont.. 1. Sub class can override the methods defined by the super class. 2. Overridden Methods in the sub classes should have same name, same signature , same return type and may have either the same or higher scope than super class method. 3. Java implements Run Time Polymorphism/ Dynamic Method Dispatch by Method Overriding. [Late Binding] 4. Call to Overridden Methods is Resolved at Run Time. 5. Call to a overridden method is not decided by the type of reference variable Rather by the type of the object where reference variable is pointing. 6. While Overriding a Method, the sub class should assign either same or higher access level than super class method.
  • 6. EXAMPLE METHOD OVERRIDING class A { void show() { System.out.println("Hello This is show() in A"); }// End of show() Method B class overrides show() method from } // End of class A super class A class B extends A { void show() { System.out.println("Hello This is show() in B"); }// End of show() Method } // End of class B class override { public static void main(String args[]) Call to show() { of A class // super class reference variable // can point to sub class object A a1 = new A(); a1.show(); Call to show() a1 = new B(); of B class a1.show(); }
  • 7. Is this Method class A Overriding { void show(int a) NO { System.out.println("Hello This is show() in A"); } } class B extends A { void show() { System.out.println("Hello This is show() in B"); } } OUTPUT Hello This is show() in A Hello This is show() in A Hello This is show() in B class override1 { public static void main(String args[]) { /* A a1 = new B(); a1.show(); */ A a1 = new A(); a1.show(10); B b1 = new B(); b1.show(10); b1.show(); }
  • 8. Dynamic Method Dispatch 1. Super class reference variable can refer to a sub class object. 2. Super class variable if refers to sub class object can call only overridden methods. 3. Call to an overridden method is decided by the type of object referred to. A a1 = new B(); a1.show(); // call to show() of B a1 = new C(); a1.show(); // call to show() of C a1 = new D(); a1.show(); // call to show() of D A B C Assume show() Method is Overridden by sub classes D
  • 9. DYNAMIC METHOD DISPATCH class A { void show() { System.out.println("Hello This is show() in A"); } } class B extends A { void show() { System.out.println("Hello This is show() in B"); } } class C extends A { void show() { System.out.println("Hello This is show() in C"); } } class D extends A { void show() { System.out.println("Hello This is show() in D"); } } CONTINUED…..
  • 10. class override2 { public static void main(String args[]) { Hello This is show() in A A a1 = new A(); Hello This is show() in B a1.show(); a1 = new B(); Hello This is show() in C a1.show(); Hello This is show() in D a1 = new C(); a1.show(); a1 = new D(); a1.show(); } }
  • 11. Method Overriding Cont.. 1. Sub class can override the methods defined by the super class. 2. Overridden Methods in the sub classes should have same name, same signature , same return type and may have either the same or higher scope than super class method. 3. Java implements Run Time Polymorphism/ Dynamic Method Dispatch by Method Overriding. [Late Binding] 4. Call to Overridden Methods is Resolved at Run Time. 5. Call to a overridden method is not decided by the type of reference variable Rather by the type of the object where reference variable is pointing. 6. While Overriding a Method, the sub class should assign either same or higher access level than super class method.
  • 12. class override3 { public static void main(String args[]) { A a1 = new B(); B b1 = (B) a1; /* A a1 = new B(); C c1 = (C) a1; Exception in thread "main" java.lang.ClassCastException: B at override3.main(override3.java:39) */ } }
  • 13. Examples Overriding class A { void show() { …. } } class B extends A { void show() { …. } void show(int x) { … } void print() { … } } A a1 = new B(); a1.show() ; // Valid // a1.show(10); // Invalid //a1.print(); // Invalid When a super class variable points to a sub class object, then it can only call overridden methods of the sub class.
  • 14. class A { protected void show() { System.out.println("Hi"); } } class B extends A { void show() { System.out.println("Hi"); } } D:Java1>javac AB.java AB.java:10: show() in B cannot override show() in A; attempting to assign weaker access privileges; was protected void show() ^ 1 error
  • 15. class A { private void show() { System.out.println("Hi"); } } class B extends A { int show() { System.out.println("Hi"); return 10; } } IS THIS METHOD OVERRIDING NO CODE WILL COMPILE & RUN SUCESSFULLY
  • 16. class A { static int show() { System.out.println("class A"); return 0; } } class B extends A { void show() { System.out.println("class B"); } } What’s Wrong Here sample.java:12: show() in B cannot override show() in A; overridden method is static void show() ^ 1 error
  • 17. Nested Classes Java programming language allows you to define a class within another class Enclosing class OuterClass Class OR { ... Outer Class A nested class is a member class NestedClass { ... of its enclosing class } } Nested Class 1.Nested has access to other members of the enclosing class,even if they are declared private 2. Can be private, public, protected or friendly access
  • 18. Nested Class Types Static nested classes 1. Static keyword applied for class declaration 2. Static nested class can use the instance fields/methods of the outer class only through object reference. 3. Static nested class can be accessed OuterClass.StaticNestedClass 4. To create an object for the static nested class, use this syntax: OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
  • 19. Nested Class Types cont.. • Non-Static nested classes 1. These nested classes do not have static keyword applied 2. Non-Static nested class can use the instance fields/methods of the outer class directly. 3. To create an object for the non-static nested class, use this syntax: OuterClass.NestedClass nestedObject = Outerobjectreference. new innerclass(); Inner class instance can only exists inside Outer class instance.
  • 20. Example 1 [Non-static Nested Class] class B class A { { int b; private int a; Outer Class Nested B(int b) A(int a) class with { { friendly int c = b+10; access this.a =a; this.b = c; } } void print() void show() { { System.out.println("a="+a) print(); ; System.out.println("b="+b); } Call to } print() of } // End of class B outer class } // End of class A
  • 21. Example 1 [Non-static Nested Class] class innertest1 { public static void main(String args[]) { A a1 = new A(10); A.B b1 = a1.new B(100); b1.show(); } } cont…. Inner class Name Outer class Reference To create an inner class instance for nonstatic classes you need an outer class reference. Inner class Reference Outer class Name If class B is Private then it is not visible in main(). A.B b1 = a1.new B(100); is WRONG/INVALID
  • 23. class A { private int a; private int b=10; A(int a) { this.a=a; } Local b B’s instance Field b A’s instance Field b void show() { B b1 = new B(30); b1.show(); } } // End of Outer class A Outer class Nested Inner class [Nonstatic Type] class B { private int b; Instance Field of B B(int b) { this.b =b; } Outer Class A’s a void show() { int b=20; System.out.println("a="+a); System.out.println("b="+b); System.out.println("this.b="+this.b); System.out.println("Outer b="+A.this.b); } } // End of B inner class
  • 24. class innerTest { public static void main(String args[]) { // Create an inner class B's instance // Call show() method // STEP 1 // Create an Outer Instance first A a1 = new A(20); A.B b1 = a1.new B(-30); b1.show(); a=20 b=20 this.b=-30 Outer b=10 // inner class object instantiation thru anonymous outer // reference A.B b2 = new A(30).new B(-40); a=30 b2.show(); b=20 } this.b=-40 } Outer b=10
  • 25. Static Inner class / Static Nested class Example class A { private int a; A(int a) { this.a =a; } void print() { System.out.println("a="+a ); } Static nested class can refere to outer members only through outer reference static class B { int b; B(int b) Static inner { class int c = b+10; this.b = c; } void show() { // print(); INVALID A a1 = new A(10); a1.print(); System.out.println("b="+b); } } // End of class B } // End of class A
  • 26. Example cont…. class innertest10 { public static void main(String args[]) { A.B b1 = new A.B(100); b1.show(); Instance of static Inner } class }
  • 27. Static Nested class Example 2 class A { private int a; protected static int b=10; A(int a) { this.a=a; } public void show() { System.out.println("a="+a); display(); } public static void display() { System.out.println("b="+b); }
  • 28. Example 2 cont…. static class B { private int a; protected static int b=100; B(int a) { this.a=a; } void show() { // A.this.show(); // Won't work show() is non-static in outer display(); // Will work as method is static in outer System.out.println("a="+a); // System.out.println("a="+A.this.a); // Won't work a is non-static in outer System.out.println("b="+b); // Will refer to its own b System.out.println("A'sb="+A.b); // will refer to outer class B new A(40).show(); // This is how you can call non static methods of outer } } // End of inner class B } // End of class A
  • 29. Example 2 cont…. class innerTest1 { public static void main(String args[]) { A.B b1 = new A.B(-30); D:jdk1.3bin>java innerTest1 b1.show(); } b=10 } a=-30 b=100 A'sb=10 a=40 b=10
  • 30. Local Inner classes [ Classes Within method body] class A { private int a; protected static int b=10; A(int a) { this.a=a; 1. } void show() 2. { class B {} 3. } } 4. Class declared within a method body. Here method is show() Local inner classes Can not be declared as public,private or protected Class B is visible only in method show(). It can be used within this show() method only Local inner classes can only use final variables from its enclosing method. However inner classes can refer to its fields of enclosing class.
  • 31. class A { private int a; protected static int b=10; A(int a) { this.a=a; } void show() { int x=10; class B { private int b; B(int b) { this.b=b; } void display() { System.out.println("a="+a); System.out.println("b="+b); System.out.println("x="+x); } } // End of class B } // End of show() method } // End of A class D:jdk1.3bin>javac innerTest2.java innerTest2.java:23: local variable x is accessed from within inner class; to be declared final System.out.println("x="+x); ^ 1 error Reference for A’s a Reference for B’s b Reference is wrong / errorneous ‘x’ is local variable inside the local method. Local classes can use only final fields from enclosing method
  • 32. class innertest { public static void main(String args[]) { final int a1=10; new A(20).show(); print(); }// End of main static void print() { /* A a1 = new A(30); a1.show(); */ System.out.println("Hello" ); } } class A { private int a; private int b; int c; A(int a) { this.a =a; b = a+20; c = a+40; } void show() { System.out.println("a1="+a1); System.out.println("a="+a); System.out.println("b="+b); System.out.println("c="+c); } } //End of A
  • 34. Anonymous Inner classes • Another category of local inner classes • Classes without any name i.e classes having no name • Can either implements an interface or extends a class. • Can not have more than one instance active at a time. • Whole body of the class is declared in a single statement ending with ;
  • 35. Cont… • Syntax [ If extending a class] [variable_type_superclass =] new superclass_name() { // properties and methods } [;] • Syntax [ If implementing an interface] [variable_type_reference =] new reference_name() { // properties and methods } [;]
  • 36. Anonymous Inner Class Example class A { private int a; A(int a) { this.a =a; } void show() { System.out.println("a="+a); } // End of show() }// End of class A
  • 37. class innertest1 { public static void main(String args[]) { Anonymous inner class extending super class A A a1 = new A(20){ public void show() { super.show(); System.out.println("Hello"); } public void display() { System.out.println("Hi"); } }; a1.show(); // a1.display(); Calling show from inner class } }
  • 38. interface X { int sum(int a,int b); int mul(int x,int y); } class innertest2 { public static void main(String args[]) { Anonymous inner class implementing an interface X x1 = new X() { public int sum(int a,int b) { return a+b; } public int mul(int a,int b) { return a*b; } }; System.out.println(x1.sum(10,20)); System.out.println(x1.mul(10,20)); }// End of main }// End of innertest2