SlideShare a Scribd company logo
1 of 28
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

More Related Content

What's hot

java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
Arjun Shanka
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10
Terry Yoast
 

What's hot (20)

C# interview quesions
C# interview quesionsC# interview quesions
C# interview quesions
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
 
inheritance
inheritanceinheritance
inheritance
 
Interface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementationInterface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementation
 
Interface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar SinghInterface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar Singh
 
Unit 3 Java
Unit 3 JavaUnit 3 Java
Unit 3 Java
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Unit 4 Java
Unit 4 JavaUnit 4 Java
Unit 4 Java
 
Interface
InterfaceInterface
Interface
 
Core java questions
Core java questionsCore java questions
Core java questions
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 
20 most important java programming interview questions
20 most important java programming interview questions20 most important java programming interview questions
20 most important java programming interview questions
 
Dacj 2-1 a
Dacj 2-1 aDacj 2-1 a
Dacj 2-1 a
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10
 
Chap11
Chap11Chap11
Chap11
 
Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
 
Top 20 c# interview Question and answers
Top 20 c# interview Question and answersTop 20 c# interview Question and answers
Top 20 c# interview Question and answers
 
C# interview
C# interviewC# interview
C# interview
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
 

Similar to Lecture 17

Corejavainterviewquestions.doc
Corejavainterviewquestions.docCorejavainterviewquestions.doc
Corejavainterviewquestions.doc
Joyce Thomas
 
1669617800196.pdf
1669617800196.pdf1669617800196.pdf
1669617800196.pdf
venud11
 

Similar to Lecture 17 (20)

Java Core Parctical
Java Core ParcticalJava Core Parctical
Java Core Parctical
 
‫‫Chapter4 Polymorphism
‫‫Chapter4 Polymorphism‫‫Chapter4 Polymorphism
‫‫Chapter4 Polymorphism
 
Corejavainterviewquestions.doc
Corejavainterviewquestions.docCorejavainterviewquestions.doc
Corejavainterviewquestions.doc
 
Core java interview questions
Core java interview questionsCore java interview questions
Core java interview questions
 
OOP in Java Presentation.pptx
OOP in Java Presentation.pptxOOP in Java Presentation.pptx
OOP in Java Presentation.pptx
 
Object Oriented Principles
Object Oriented PrinciplesObject Oriented Principles
Object Oriented Principles
 
Selenium Training .pptx
Selenium Training .pptxSelenium Training .pptx
Selenium Training .pptx
 
Learn java objects inheritance-overriding-polymorphism
Learn java objects  inheritance-overriding-polymorphismLearn java objects  inheritance-overriding-polymorphism
Learn java objects inheritance-overriding-polymorphism
 
البرمجة الهدفية بلغة جافا - تعدد الأشكال
البرمجة الهدفية بلغة جافا - تعدد الأشكالالبرمجة الهدفية بلغة جافا - تعدد الأشكال
البرمجة الهدفية بلغة جافا - تعدد الأشكال
 
Basic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobBasic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a job
 
Learn Polymorphism in Python with Examples.pdf
Learn Polymorphism in Python with Examples.pdfLearn Polymorphism in Python with Examples.pdf
Learn Polymorphism in Python with Examples.pdf
 
Object+oriented+programming+in+java
Object+oriented+programming+in+javaObject+oriented+programming+in+java
Object+oriented+programming+in+java
 
1669617800196.pdf
1669617800196.pdf1669617800196.pdf
1669617800196.pdf
 
Learn java lessons_online
Learn java lessons_onlineLearn java lessons_online
Learn java lessons_online
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Classes2
Classes2Classes2
Classes2
 
Java Core
Java CoreJava Core
Java Core
 
Delphi qa
Delphi qaDelphi qa
Delphi qa
 
Chapter8:Understanding Polymorphism
Chapter8:Understanding PolymorphismChapter8:Understanding Polymorphism
Chapter8:Understanding Polymorphism
 
116824015 java-j2 ee
116824015 java-j2 ee116824015 java-j2 ee
116824015 java-j2 ee
 

More from talha ijaz (15)

Lecture 23-24.pptx
Lecture 23-24.pptxLecture 23-24.pptx
Lecture 23-24.pptx
 
Lecture 22
Lecture 22Lecture 22
Lecture 22
 
Lecture 20-21
Lecture 20-21Lecture 20-21
Lecture 20-21
 
Lecture 19
Lecture 19Lecture 19
Lecture 19
 
Lecture 18
Lecture 18Lecture 18
Lecture 18
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
 
Lecture 7
Lecture 7Lecture 7
Lecture 7
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
Visual perception
Visual perceptionVisual perception
Visual perception
 
Lecture 11
Lecture 11Lecture 11
Lecture 11
 
Introduction
IntroductionIntroduction
Introduction
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
Lecture 1
Lecture 1Lecture 1
Lecture 1
 

Recently uploaded

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 

Recently uploaded (20)

Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 

Lecture 17

  • 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 & 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
  • 6. 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
  • 7. 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
  • 8. 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
  • 9. 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
  • 10. 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
  • 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
  • 13. Polymorphism Method Lookup with Inheritance This scenario illustrates how objects inherit methods. 13
  • 14. Polymorphism Method Lookup with Polymorphism & Overriding 14
  • 15. Polymorphism Redefining Display Method public void 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
  • 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 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
  • 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
  • 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. 28