Lecture-17
Instructor Name:
Object Oriented Programming
Today’s Lecture
 Polymorphism
2
Polymorphism
What is 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.
 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.
3
Polymorphism
What is Polymorphism?
 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.
 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.
4
Polymorphism
Static & Dynamic Type
 Trying to solve problem of developing a complete polymorphic display
method leads into discussion of static and dynamic types and method
lookup.
 At first attempt to solve this problem might be to move display method in
Photopost and MessagePost
 Do you think your application will compile anymore?
 We get errors in the MessagePost and PhotoPost classes, because we cannot
access the superclass fields.
 We get an error in the NewsFeed class, because it cannot find the display
method.
5
Polymorphism
Static & Dynamic Type
 The reason for the first sort of error is that the fields in Post have private
access and so are inaccessible to any other class—including subclasses.
 In order to keep maintaining encapsulation the easiest way to solve this is to
define public accessor methods for them.
6
Polymorphism
Static & Dynamic Type
Recall the display method called in NewsFeed Class
for(Post post : posts) {
post.display();
System.out.println();
}
 The compiler informs display does not exist in post.
 Every Post object in the collection is in fact a MessagePost or a PhotoPost
object, and both have display methods
 This should mean that post.display() ought to work, because, whatever it is—
MessagePost or PhotoPost—we know that it does have a display method. 7
Polymorphism
Static & Dynamic Type
 To understand in detail
 Car c1 = new Car();
 type of c1 is Car
 Consider the following statement:
 Vehicle v1 = new Car();
 What is the type of v1?
 The type of the variable v1 is Vehicle;
 The type of the object stored in v1 is Car.
 Through sub-typing and substitution rules --Allowed,
 we now have situations where the type of the variable and the type of the
object stored in it are not exactly the same
8
Polymorphism
Static & Dynamic Type
 We come up with two concepts Static & Dynamic types
 The static type of a variable v is the type as declared in the source code in the
variable declaration statement.
 The dynamic type of a variable v is the type of the object that is currently
stored in v
 More precise: the static type of v1 is Vehicle, the dynamic type of v1 is Car.
 In Our example the static type of post is Post, while the dynamic type is
either MessagePost or PhotoPost.
 We do not know which one of these it is, assuming that we have entered both
MessagePost and PhotoPost objects into the feed.
9
Polymorphism
Static & Dynamic Type
 The compiler reports an error because, for type checking, the static type is
used.
 The dynamic type is often only known at runtime, so the compiler has no
other choice but to use the static type
 if it wants to do any checks at compile time. The static type of post is Post,
and Post does not have a display method.
 The behavior of the compiler is reasonable in this respect, because it has no
guarantee that all subclasses of Post will, indeed, define a display method,
and this is impossible to check in practice.
 The technique to handle such kind of problem is method overriding.
10
Polymorphism
Dynamic Method Lookup
 Type checking uses the static type, but at runtime, the methods from
the dynamic type are executed.
 This is a fairly important statement.
 To understand it better, we look in more detail at how methods are
invoked.
 This procedure is known as method lookup, method binding, or
method dispatch..
11
Polymorphism
Method Lookup with Simple Object
12
Polymorphism
Method Lookup with Inheritance
This scenario illustrates how objects inherit methods.
13
Polymorphism
Method Lookup with Polymorphism & Overriding
14
Polymorphism
Redefining Display Method
public void display()
{
super.display();
System.out.println(" ["+ filename + "]");
System.out.println(" "+ caption);
}
15
Access Modifiers
Protected Access
 In OOP a level of access lies between the complete restriction of private
access and the full availability of public access
 Declaring a field or a method protected allows direct access to it from (direct
or indirect) subclasses.
protected long getTimeStamp()
{
return timestamp;
}
 Protected access allows access to the fields or methods within a class itself
and from all its subclasses, but not from other classes
16
Access Modifiers
Access Levels
17
Access Modifiers
Access Levels
 While protected access can be applied to any member of a class, it is usually
reserved for methods and constructors.
 It is not usually applied to fields, because that would be a weakening of
encapsulation.
 Wherever possible, mutable fields in super classes should remain private.
 There are, however, occasional valid cases where direct access by subclasses
is desirable.
18
Access Modifiers
Access Control & Inheritance
 The following rules for inherited methods are enforced:
 Methods declared public in a superclass also must be public in all
subclasses.
 Methods declared protected in a superclass must either be protected or
public in subclasses; they cannot be private.
 Methods declared without access control (no modifier was used) can be
declared more private in subclasses.
 Methods declared private are not inherited at all, so there is no rule for
them. 19
Final Keyword
Final Keyword in Java
 The final keyword in java is used to restrict the user. The java final keyword
can be used in many context. Final can be:
1. variable
2. method
3. class
 The final keyword can be applied with the variables, a final variable that
have no value it is called blank final variable or uninitialized final variable.
 It can be initialized in the constructor only.
 The blank final variable can be static also which will be initialized in the
static block only.
 I f you make any variable as final, you cannot change the value of final
variable(It will be constant).
20
Final Keyword
Final Keyword – Example Code
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
 Output – Compile time error
21
Final Keyword
Final Methods & Final Classes
 If a method is declared final , it not be overridden
 If a class is final , it can not be extended
 Final method is inherited but it can not override
 If declare any parameter as final we can not change the value of it
 A constructor can not be declare as final
22
Static Keyword
Static Keyword
 The static keyword in java is used for memory management mainly.
 We can apply java static keyword with variables, methods, blocks and nested
class.
 The static keyword belongs to the class than instance of the class.
 The static can be:
1. variable (also known as class variable)
2. method (also known as class method)
3. block
4. nested class
23
Static Keyword
Static Variable
 If declare any variable as static, it is known static variable.
 The static variable can be used to refer the common property of all objects
(that is not unique for each object) e.g. company name of employees,college
name of students etc.
 The static variable gets memory only once in class area at the time of class
loading.
 Advantage of Static Variable is that It makes your program memory
efficient (i.e it saves memory).
 Suppose there are 500 students in my college, now all instance data members
will get memory each time when object is created.All student have its unique
rollno and name so instance data member is good.Here, college refers to the
common property of all objects.If we make it static,this field will get memory
only once.
24
Static Keyword
Static Variable
25
Static Keyword
Static Methods
 If you apply static keyword with any method, it is known as static
method.
– A static method belongs to the class rather than object of a class.
– A static method can be invoked without the need for creating an
instance of a class.
– static method can access static data member and can change the
value of it.
Restrictions
 There are two main restrictions for the static method. They are:
1. The static method can not use non static data member or call non-static
method directly.
2. this and super cannot be used in static context.
26
Static Keyword
Static Block
 Is used to initialize the static data member.
 It is executed before main method at the time of class loading.
27
28

Lecture 17

  • 1.
  • 2.
  • 3.
    Polymorphism What is 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.  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. 3
  • 4.
    Polymorphism What is Polymorphism? 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.  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. 4
  • 5.
    Polymorphism Static & DynamicType  Trying to solve problem of developing a complete polymorphic display method leads into discussion of static and dynamic types and method lookup.  At first attempt to solve this problem might be to move display method in Photopost and MessagePost  Do you think your application will compile anymore?  We get errors in the MessagePost and PhotoPost classes, because we cannot access the superclass fields.  We get an error in the NewsFeed class, because it cannot find the display method. 5
  • 6.
    Polymorphism Static & DynamicType  The reason for the first sort of error is that the fields in Post have private access and so are inaccessible to any other class—including subclasses.  In order to keep maintaining encapsulation the easiest way to solve this is to define public accessor methods for them. 6
  • 7.
    Polymorphism Static & DynamicType Recall the display method called in NewsFeed Class for(Post post : posts) { post.display(); System.out.println(); }  The compiler informs display does not exist in post.  Every Post object in the collection is in fact a MessagePost or a PhotoPost object, and both have display methods  This should mean that post.display() ought to work, because, whatever it is— MessagePost or PhotoPost—we know that it does have a display method. 7
  • 8.
    Polymorphism Static & DynamicType  To understand in detail  Car c1 = new Car();  type of c1 is Car  Consider the following statement:  Vehicle v1 = new Car();  What is the type of v1?  The type of the variable v1 is Vehicle;  The type of the object stored in v1 is Car.  Through sub-typing and substitution rules --Allowed,  we now have situations where the type of the variable and the type of the object stored in it are not exactly the same 8
  • 9.
    Polymorphism Static & DynamicType  We come up with two concepts Static & Dynamic types  The static type of a variable v is the type as declared in the source code in the variable declaration statement.  The dynamic type of a variable v is the type of the object that is currently stored in v  More precise: the static type of v1 is Vehicle, the dynamic type of v1 is Car.  In Our example the static type of post is Post, while the dynamic type is either MessagePost or PhotoPost.  We do not know which one of these it is, assuming that we have entered both MessagePost and PhotoPost objects into the feed. 9
  • 10.
    Polymorphism Static & DynamicType  The compiler reports an error because, for type checking, the static type is used.  The dynamic type is often only known at runtime, so the compiler has no other choice but to use the static type  if it wants to do any checks at compile time. The static type of post is Post, and Post does not have a display method.  The behavior of the compiler is reasonable in this respect, because it has no guarantee that all subclasses of Post will, indeed, define a display method, and this is impossible to check in practice.  The technique to handle such kind of problem is method overriding. 10
  • 11.
    Polymorphism Dynamic Method Lookup Type checking uses the static type, but at runtime, the methods from the dynamic type are executed.  This is a fairly important statement.  To understand it better, we look in more detail at how methods are invoked.  This procedure is known as method lookup, method binding, or method dispatch.. 11
  • 12.
  • 13.
    Polymorphism Method Lookup withInheritance This scenario illustrates how objects inherit methods. 13
  • 14.
    Polymorphism Method Lookup withPolymorphism & Overriding 14
  • 15.
    Polymorphism Redefining Display Method publicvoid display() { super.display(); System.out.println(" ["+ filename + "]"); System.out.println(" "+ caption); } 15
  • 16.
    Access Modifiers Protected Access In OOP a level of access lies between the complete restriction of private access and the full availability of public access  Declaring a field or a method protected allows direct access to it from (direct or indirect) subclasses. protected long getTimeStamp() { return timestamp; }  Protected access allows access to the fields or methods within a class itself and from all its subclasses, but not from other classes 16
  • 17.
  • 18.
    Access Modifiers Access Levels While protected access can be applied to any member of a class, it is usually reserved for methods and constructors.  It is not usually applied to fields, because that would be a weakening of encapsulation.  Wherever possible, mutable fields in super classes should remain private.  There are, however, occasional valid cases where direct access by subclasses is desirable. 18
  • 19.
    Access Modifiers Access Control& Inheritance  The following rules for inherited methods are enforced:  Methods declared public in a superclass also must be public in all subclasses.  Methods declared protected in a superclass must either be protected or public in subclasses; they cannot be private.  Methods declared without access control (no modifier was used) can be declared more private in subclasses.  Methods declared private are not inherited at all, so there is no rule for them. 19
  • 20.
    Final Keyword Final Keywordin Java  The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be: 1. variable 2. method 3. class  The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or uninitialized final variable.  It can be initialized in the constructor only.  The blank final variable can be static also which will be initialized in the static block only.  I f you make any variable as final, you cannot change the value of final variable(It will be constant). 20
  • 21.
    Final Keyword Final Keyword– Example Code class Bike9{ final int speedlimit=90;//final variable void run(){ speedlimit=400; } public static void main(String args[]){ Bike9 obj=new Bike9(); obj.run(); } }//end of class  Output – Compile time error 21
  • 22.
    Final Keyword Final Methods& Final Classes  If a method is declared final , it not be overridden  If a class is final , it can not be extended  Final method is inherited but it can not override  If declare any parameter as final we can not change the value of it  A constructor can not be declare as final 22
  • 23.
    Static Keyword Static Keyword The static keyword in java is used for memory management mainly.  We can apply java static keyword with variables, methods, blocks and nested class.  The static keyword belongs to the class than instance of the class.  The static can be: 1. variable (also known as class variable) 2. method (also known as class method) 3. block 4. nested class 23
  • 24.
    Static Keyword Static Variable If declare any variable as static, it is known static variable.  The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees,college name of students etc.  The static variable gets memory only once in class area at the time of class loading.  Advantage of Static Variable is that It makes your program memory efficient (i.e it saves memory).  Suppose there are 500 students in my college, now all instance data members will get memory each time when object is created.All student have its unique rollno and name so instance data member is good.Here, college refers to the common property of all objects.If we make it static,this field will get memory only once. 24
  • 25.
  • 26.
    Static Keyword Static Methods If you apply static keyword with any method, it is known as static method. – A static method belongs to the class rather than object of a class. – A static method can be invoked without the need for creating an instance of a class. – static method can access static data member and can change the value of it. Restrictions  There are two main restrictions for the static method. They are: 1. The static method can not use non static data member or call non-static method directly. 2. this and super cannot be used in static context. 26
  • 27.
    Static Keyword Static Block Is used to initialize the static data member.  It is executed before main method at the time of class loading. 27
  • 28.