java notes important

36
O O P s (Object O rien t ed P rogr am mingS ys tem) Object means a r eal word entity such as pen, chair , table etc. Object-Oriente d Programming is a methodology or paradigm to design a program using classes and objects. It simplifies the software development and maintenance by providing some concepts: Object Class Inheritance Polymorphism Abstraction ncapsulation Obj ect Any entity that has state and behavior is !nown as an object. "or e#ample: chair, pen, table, !eyboard, bi!e etc. It can be physical and logical. C l ass Collection of objects is called class. It is a logical entity. I n h e r i t a n c e When one object acquires all the properties and behaviours of parent object  i.e. !nown as inheritance. It provides code reusability . It is used to achieve runtime polymorphism. P o l ym o r p hi sm $hen one task is performed by different ways i.e. !nown as polymorphism. "or e#ample: to convense the customer differently, to draw something e.g. shape or r ectangle etc. In java, we use method overloading and method overriding to achieve polymorphism. Another e#ample can be to spea! something e.g. cat spea!s meaw, dog bar!s woof etc. A b s t ra c t i o n Hiding internal details and showing functionality is !nown as abstraction. "or e#ample: phone call, we don%t !now the internal processing. In java, we use abstract class and interface to achieve abstraction.  E n ca p sulatio n inding !or wrapping" code and data together into a single unit is known as encapsulation. "or e#ample: capsule, it is wrapped with different medicines. A java class is the e#ample of encapsulation. &ava bean is the fully encapsulated class because all the data members are private here. A dva n t ag e of O O P s over P r o cedur e - o ri e nte d p r og r am m i ng l a ng ua ge '(OOPs ma!es development and maintenance easier where as in Procedure)oriented programming language it is not easy to manage if code grows as project si*e grows. +(OOPs provides data hiding whereas in Procedure)oriented pr gramming language a global data can be accessed from anywhere.

Upload: srikanthallam123

Post on 21-Feb-2018

225 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Java Notes important

7/24/2019 Java Notes important

http://slidepdf.com/reader/full/java-notes-important 1/36

OOPs (Object Oriented Programming System)Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a

methodology or paradigm to design a program using classes and objects. It simplifies the software

development and maintenance by providing some concepts:

• Object

• Class

• Inheritance

• Polymorphism

• Abstraction

• ncapsulation

Object

Any entity that has state and behavior is !nown as an object. "or e#ample: chair, pen, table,

!eyboard, bi!e etc. It can be physical and logical.

Class

Collection of objects is called class. It is a logical entity.

Inheritance

When one object acquires all the properties and behaviours of parent object i.e. !nown as

inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

Polymorphism

$hen one task is performed by different ways i.e. !nown as polymorphism. "or e#ample: to

convense the customer differently, to draw something e.g. shape or rectangle etc.

In java, we use method overloading and method overriding to achieve polymorphism.

Another e#ample can be to spea! something e.g. cat spea!s meaw, dog bar!s woof etc.

Abstraction

Hiding internal details and showing functionality is !nown as abstraction. "or e#ample: phone

call, we don%t !now the internal processing.

In java, we use abstract class and interface to achieve abstraction. 

Encapsulationinding !or wrapping" code and data together into a single unit is known as

encapsulation. "or e#ample: capsule, it is wrapped with different medicines.

A java class is the e#ample of encapsulation. &ava bean is the fully encapsulated class because all

the data members are private here.

Advantage of OOPs over Procedure-oriented programming language

'(OOPs ma!es development and maintenance easier where as in Procedure)oriented

programming language it is not easy to manage if code grows as project si*e grows.+(OOPs provides data hiding whereas in Procedure)oriented prgramming language a global data

can be accessed from anywhere.

Page 2: Java Notes important

7/24/2019 Java Notes important

http://slidepdf.com/reader/full/java-notes-important 2/36

(OOPs provides ability to simulate real)world event much more effectively. $e can provide the

solution of real word problem if we are using the Object)Oriented Programming language.

What is difference between object-oriented programming language and object-

based programming language?

Object based programming language follows all the features of OOPs e#cept Inheritance.&ava-cript and /-cript are e#amples of object based programming languages.

Object in Java

An entity that has state and behavior is !nown as an object e.g. chair, bi!e, mar!er, pen, table, car

etc. It can be physical or logical 0tengible and intengible(. 1he e#ample of integible object is ban!ingsystem.

An object has three characteristics:

•   state# represents data 0value( of an object.

•   behavior# represents the behavior 0functionality( of an object such as deposit, withdraw etc.

•   identity# Object identity is typically implemented via a uni2ue I3. 1he value of the I3 is not

visible to the e#ternal user. /ut,it is used internally by the &4 to identify each objectuni2uely.

"or #ample: Pen is an object. Its name is 5eynolds, color is white etc. !nown as its state. It is

used to write, so writing is its behavior.

Object is an instance of a class$ Class is a template or blueprint from which objects are

created. -o object is the instance0result( of a class.

Class in JavaA class is a group of objects that has common properties. It is a template or blueprint from which

objects are created.

A class in java can contain:

•   data member

•   method

Page 3: Java Notes important

7/24/2019 Java Notes important

http://slidepdf.com/reader/full/java-notes-important 3/36

•   constructor

•   block

•   class and interface

Syntax to declare a class:'.   class 6class7name89

+. data member. method

;. <Simple Example of Object and Class

In this e#ample, we have created a -tudent class that have two data members id and name. $e are

creating the object of the -tudent class by new !eyword and printing the objects value.

'.   class -tudent9+. int id ==data member 0also instance variable( . -tring name ==data member0also instance variable( ;.>. public static void main0-tring args?@(9

. -tudent s'Bnew -tudent0( ==creating an object of -tudent . -ystem.out.println0s'.idDE EDs'.name(F.

G. <'H. <

Output:0 null

 

Instance variable in Java

A variable that is created inside the class but outside the method, is !nown as instance

variable.Instance variable doesn%t get memory at compile time.It gets memory at runtime when

object0instance( is created.1hat is why, it is !nown as instance variable.

Method in Java

In java, a method is li!e function i.e. used to e#pose behaviour of an object.

Advantage of Method

• Code 5eusability

• Code Optimi*ation

new keyword

1he new !eyword is used to allocate memory at runtime.

Example of Object and class that maintains the

records of students

In this e#ample, we are creating the two objects of -tudent class and initiali*ing the value to

these objects by invo!ing the insert5ecord method on it. ere, we are displaying the state 0data(

of the objects by invo!ing the displayInformation method.

'.   class -tudent9+. int rollno. -tring name;.

>. void insert5ecord0int r, -tring n(9  ==method 

Page 4: Java Notes important

7/24/2019 Java Notes important

http://slidepdf.com/reader/full/java-notes-important 4/36

. rollnoBr

. nameBnF. <

G.'H. void displayInformation0(9-ystem.out.println0rollnoDE EDname(< ==method ''.'+. public static void main0-tring args?@(9'. -tudent s'Bnew -tudent0(

';. -tudent s+Bnew -tudent0('>.'. s'.insert5ecord0''',EJaranE(

'. s+.insert5ecord0+++,EAryanE('F.

'G. s'.displayInformation0(+H. s+.displayInformation0(+'.++. <+. <

Output:111 Karan

  222 Aryan

 

As you see in the above figure, object gets the memory in eap area and reference variable

refers to the object allocated in the eap memory area. ere, s' and s+ both are reference

variables that refer to the objects allocated in memory.

Another Example of Object and Class

1here is given another e#ample that maintains the records of 5ectangle class. Its e#aplanation is

same as in the above -tudent class e#ample.

'.   class 5ectangle9+. int length

. int width;.

>. void insert0int l,int w(9. lengthBl. widthBwF. <G.'H. void calculateArea0(9-ystem.out.println0lengthKwidth(<''.'+. public static void main0-tring args?@(9

'. 5ectangle r'Bnew 5ectangle0(';. 5ectangle r+Bnew 5ectangle0(

'>.'. r'.insert0'',>(

'. r+.insert0,'>('F.'G. r'.calculateArea0(

Page 5: Java Notes important

7/24/2019 Java Notes important

http://slidepdf.com/reader/full/java-notes-important 5/36

+H. r+.calculateArea0(

+'. <++. <

Output:55

45

What are the different ways to create an object in Java?

1here are many ways to create an object in java. 1hey are:

• /y new !eyword

• /y newInstance0( method

• /y clone0( method

• /y factory method etc.

$e will learn, these ways to create the object later.

Annonymous object

Annonymous simply means nameless.An object that have no reference is !nown as annonymous

object.

If you have to use an object only once, annonymous object is a good approach.

'.   class Calculation9+.

. void fact0int  n(9;. int factB'

>. for0int iB'i6BniDD(9. factBfactKi

. <F. -ystem.out.println0Efactorial is EDfact(G. <

'H.''.   public static void main0-tring args?@(9'+. new Calculation0(.fact0>( ==calling method with annonymous object '. <';. <

Output:Factorial is 120

Creating multiple objects by one type only

$e can create multiple objects by one type only as we do in case of primitives.

'. 5ectangle r'Bnew 5ectangle0(,r+Bnew 5ectangle0( ==creating two objects 

Let%s see the e#ample:'.   class 5ectangle9+. int length

. int width;.>. void insert0int l,int w(9. lengthBl. widthBwF. <

G.'H. void calculateArea0(9-ystem.out.println0lengthKwidth(<

''.

'+. public static void main0-tring args?@(9'. 5ectangle r'Bnew 5ectangle0(,r+Bnew 5ectangle0( ==creating two objects ';.'>. r'.insert0'',>('. r+.insert0,'>(

Page 6: Java Notes important

7/24/2019 Java Notes important

http://slidepdf.com/reader/full/java-notes-important 6/36

'.

'F. r'.calculateArea0('G. r+.calculateArea0(

+H. <+'. <

Output:55

45

Method Overloading in Java

If a class have multiple methods by same name but different parameters, it is !nown as %ethod

Overloading.

If we have to perform only one operation, having same name of the methods increases the

readability of the program.

-uppose you have to perform addition of the given numbers but there can be any number of 

arguments, if you write the method such as a0int,int( for two parameters, and b0int,int,int( for three

parameters then it may be difficult for you as well as other programmers to understand the

behaviour of the method because its name differs. -o, we perform method overloading to figure out

the program 2uic!ly.

Advantage of method overloading?

4ethod overloading increases the readability of the program.

Different ways to overload the method

1here are two ways to overload the method in java

'. /y changing number of arguments

+. /y changing the data type

In java, Methood Overloading is not possible by changing the return type of the method.

1)Example of Method Overloading by changing the no

of arguments

In this e#ample, we have created two overloaded methods, first sum method performs addition of

two numbers and second sum method performs addition of three numbers.

'.   class Calculation9

+. void sum0int a,int b(9-ystem.out.println0aDb(<. void sum0int a,int b,int c(9-ystem.out.println0aDbDc(<

;.>. public static void main0-tring args?@(9

Page 7: Java Notes important

7/24/2019 Java Notes important

http://slidepdf.com/reader/full/java-notes-important 7/36

. Calculation objBnew Calculation0(

. obj.sum0'H,'H,'H(F. obj.sum0+H,+H(

G.'H. <''. <

Output:30

  40

!)Example of Method Overloading by changing data

type of argument

In this e#ample, we have created two overloaded methods that differs in data type. 1he first sum

method receives two integer arguments and second sum method receives two double arguments.

'.   class Calculation9+. void sum0int a,int b(9-ystem.out.println0aDb(<. void sum0double a,double b(9-ystem.out.println0aDb(<;.

>. public static void main0-tring args?@(9. Calculation objBnew Calculation0(

. obj.sum0'H.>,'H.>(F. obj.sum0+H,+H(G.'H. <''. <

Output:21.0

  40

Que) Why Method Overloaing is not possible by changing the return type of method?

In java, method overloading is not possible by changing the return type of the method because

there may occur ambiguity. Let%s see how ambiguity may occur:

because there was problem:

'.   class Calculation9+. int sum0int a,int b(9-ystem.out.println0aDb(<. double sum0int a,int b(9-ystem.out.println0aDb(<;.>. public static void main0-tring args?@(9

. Calculation objBnew Calculation0(. int resultBobj.sum0+H,+H( ==Compile 1ime rror 

F.G. <'H. <

int resultBobj.sum0+H,+H( ==ere how can java determine which sum0( method should be called

Page 8: Java Notes important

7/24/2019 Java Notes important

http://slidepdf.com/reader/full/java-notes-important 8/36

Can we overload main() method?

Mes, by method overloading. Mou can have any number of main methods in a class by method

overloading. Let%s see the simple e#ample:

'.   class -imple9+. public static void main0int a(9

. -ystem.out.println0a(;. <>.. public static void main0-tring args?@(9. -ystem.out.println0Emain0( method invo!edE(F. main0'H(G. <'H. <

Output:main() method ino!ed

  10

Constructor in Java

Constructor is a special type of method that is used to initiali*e the object.

Constructor is invoked at the time of object creation. It constructs the values i.e. provides data

for the object that is why it is !nown as constructor.

Rules for creating constructor

1here are basically two rules defined for the constructor.

'. Constructor name must be same as its class name+. Constructor must have no e#plicit return type

Types of constructors

1here are two types of constructors:

'. default constructor 0no)arg constructor(+. parameteri*ed constructor

1) Default ConstructorA constructor that have no parameter is !nown as default constructor.

Page 9: Java Notes important

7/24/2019 Java Notes important

http://slidepdf.com/reader/full/java-notes-important 9/36

Syntax of default constructor:'. 6class7name80(9<

Example of default constructor

In this e#ample, we are creating the no)arg constructor in the /i!e class. It will be invo!ed at the

time of object creation.

'.   class /i!e9

+.. /i!e0(9-ystem.out.println0E/i!e is createdE(<;.>.   public static void main0-tring args?@(9. /i!e bBnew /i!e0(

. <F. <

Output: "i!e is created

Rule: If there is no constructor in a class, compiler automatically creates a default constructor.

Que)What is the purpose of default constructor?

3efault constructor provides the default values to the object li!e H, null etc. depending on the type.

Example of default constructor that displays thedefault values

'.   class -tudent9+.   int id. -tring name;.>.   void display0(9-ystem.out.println0idDE EDname(<..   public static void main0-tring args?@(9

F. -tudent s'Bnew -tudent0(G. -tudent s+Bnew -tudent0(

'H. s'.display0(''. s+.display0('+. <'. <

Output:0 null

  0 null

&'planation#In the above class,you are not creating any constructor so compiler provides you a

default constructor.ere H and null values are provided by default constructor.

Parameterized constructorA constructor that have parameters is !nown as parameteri*ed constructor.

Page 10: Java Notes important

7/24/2019 Java Notes important

http://slidepdf.com/reader/full/java-notes-important 10/36

Why use parameterized constructor?

Parameteri*ed constructor is used to provide different values to the distinct objects.

Example of parameteri"ed constructor

In this e#ample, we have created the constructor of -tudent class that have two parameters. $e

can have any number of parameters in the constructor.

'.   class -tudent9+. int id. -tring name;.>. -tudent0int i,-tring n(9. id B i

. name B nF. <

G. void display0(9-ystem.out.println0idDE EDname(<'H.''. public static void main0-tring args?@(9

'+. -tudent s' B new -tudent0''',EJaranE(

'. -tudent s+ B new -tudent0+++,EAryanE(';. s'.display0('>. s+.display0('. <

'. <

Output:111 Karan

  222 Aryan

Constructor Overloading

Constructor overloading is a techni2ue in &ava in which a class can have any number of

constructors that differ in parameter lists.1he compiler differentiates these constructors by ta!ing

into account the number of parameters in the list and their type.

Example of Constructor Overloading'.   class -tudent9+. int id. -tring name;. int age>. -tudent0int i,-tring n(9. id B i. name B n

F. <

G. -tudent0int i,-tring n,int a(9'H. id B i''. name B n'+. ageBa'. <';. void display0(9-ystem.out.println0idDE EDnameDE EDage(<'>.'. public static void main0-tring args?@(9

'. -tudent s' B new -tudent0''',EJaranE(

'F. -tudent s+ B new -tudent0+++,EAryanE,+>(

'G. s'.display0(

+H. s+.display0(

+'. <++. <

Output:111 Karan 0

  222 Aryan 25

Page 11: Java Notes important

7/24/2019 Java Notes important

http://slidepdf.com/reader/full/java-notes-important 11/36

What is the difference between constructor and method ?

1here are many differences between constructors and methods. 1hey are given below.

Constructor %ethod

Constructor is used to initiali*e the state of anobject.

4ethod is used to e#posebehaviour of an object.

Constructor must not have return type. 4ethod must have return type.

Constructor is invo!ed implicitly. 4ethod is invo!ed e#plicitly.

1he java compiler provides a default constructor if

you don%t have any constructor.

4ethod is not provided by compiler

in any case.

Constructor name must be same as the class

name.

4ethod name may or may not be

same as class name.

Copying the values of one object to another like copy constructor

in C++

1here are many ways to copy the values of one object into another. 1hey are:

• /y constructor

• /y assigning the values of one object into another

• /y clone0( method of Object class

In this e#ample, we are going to copy the values of one object into another using constructor.

'.   class -tudent9

+. int id. -tring name;. -tudent0int i,-tring n(9>. id B i. name B n. <F.G. -tudent0-tudent s(9

'H. id B s.id''. name Bs.name

'+. <'. void display0(9-ystem.out.println0idDE EDname(<

';.'>. public static void main0-tring args?@(9

'. -tudent s' B new -tudent0''',EJaranE(

'. -tudent s+ B new -tudent0s'('F. s'.display0(

'G. s+.display0(+H. <

Page 12: Java Notes important

7/24/2019 Java Notes important

http://slidepdf.com/reader/full/java-notes-important 12/36

+'. <

Output:111 Karan

  111 Karan

Copying the values of one object to another without constructor

$e can copy the values of one object into another by assigning the objects values to another

object. In this case, there is no need to create the constructor.

'.   class -tudent9+. int id. -tring name;. -tudent0int i,-tring n(9>. id B i. name B n. <

F. -tudent0(9<G. void display0(9-ystem.out.println0idDE EDname(<

'H.''. public static void main0-tring args?@(9

'+. -tudent s' B new -tudent0''',EJaranE('. -tudent s+ B new -tudent0(';. s+.idBs'.id

'>. s+.nameBs'.name'. s'.display0(

'. s+.display0('F. <'G. <

Output:111 Karan

  111 Karan

Que)Does constructor return any value?

(ns#yes,that is current class instance 0Mou cannot use return type yet it returns a value(.

Can constructor perform other tasks instead of initialization?

Mes, li!e object creation, starting a thread, calling method etc. Mou can perform any operation in the

constructor as you perform in the method.

1he static keyword is used in java mainly for memory management. $e may apply static !eyword

with variables, methods, bloc!s and nested class. 1he static !eyword belongs to the class than

instance of the class.

1he static can be:

'. variable 0also !nown as class variable(+. method 0also !nown as class method(

. bloc!

;. nested class

Page 13: Java Notes important

7/24/2019 Java Notes important

http://slidepdf.com/reader/full/java-notes-important 13/36

1) static variable

If you declare any variable as static, it is !nown static variable.

• 1he static variable can be used to refer the common property of all objects 0that is not

uni2ue for each object( e.g. company name of employees,college name of students etc.

• 1he static variable gets memory only once in class area at the time of class loading.

Advantage of static variable

It ma!es your program memory efficient 0i.e it saves memory(.

Understanding problem without static variable

'.   class -tudent9+. int rollno

. -tring name;. -tring collegeBEI1-E

>. <

-uppose there are >HH students in my college, now all instance data members will get memory eachtime when object is created.All student have its uni2ue rollno and name so instance data member is

good.ere, college refers to the common property of all objects.If we ma!e it static,this field will get

memory only once.

static property is shared to all objects.

Example of static variable'.  ==Program of static variable 

+..   class -tudent9

;. int rollno>. -tring name

. static -tring college BEI1-E.F. -tudent0int r,-tring n(9G. rollno B r'H. name B n''. <'+. void display 0(9-ystem.out.println0rollnoDE EDnameDE EDcollege(<'.

';. public static void main0-tring args?@(9'>. -tudent s' B new -tudent 0''',EJaranE(

'. -tudent s+ B new -tudent 0+++,EAryanE('.'F. s'.display0('G. s+.display0(+H. <+'. <

Output:111 Karan #$%

  222 Aryan #$%

Page 14: Java Notes important

7/24/2019 Java Notes important

http://slidepdf.com/reader/full/java-notes-important 14/36

Page 15: Java Notes important

7/24/2019 Java Notes important

http://slidepdf.com/reader/full/java-notes-important 15/36

'>. <<

Output:1

  2

  3

2) static method

If you apply static !eyword with any method, it is !nown as static method

• A static method belongs to the class rather than object of a class.

• A static method can be invo!ed without the need for creating an instance of a class.

• static method can access static data member and can change the value of it.

Example of static method'.  ==Program of changing the common property of all objects0static field(. +..   class -tudent9

;. int rollno>. -tring name. static -tring college B EI1-E.F. static void change0(9

G. college B E//3I1E'H. <

''.'+. -tudent0int r, -tring n(9'. rollno B r';. name B n'>. <'.'. void display 0(9-ystem.out.println0rollnoDE EDnameDE EDcollege(<'F.

'G. public static void main0-tring args?@(9+H. -tudent.change0(

+'.++. -tudent s' B new -tudent 0''',EJaranE(

+. -tudent s+ B new -tudent 0+++,EAryanE(+;. -tudent s B new -tudent 0,E-onooE(+>.+. s'.display0(+. s+.display0(+F. s.display0(

+G. <H. <

Output:111 Karan ""&#$

  222 Aryan ""&#$

  333 %onoo ""&#$

Another example of static method that performs

normal calculation'.  ==Program to get cube of a given number by static method 

+..   class Calculate9

;. static int cube0int #(9>. return #K#K#. <

Page 16: Java Notes important

7/24/2019 Java Notes important

http://slidepdf.com/reader/full/java-notes-important 16/36

.

F. public static void main0-tring args?@(9G. int resultBCalculate.cube0>(

'H. -ystem.out.println0result(''. <'+. <

Output:125

Restrictions for static method1here are two main restrictions for the static method. 1hey are:

'. 1he static method can not use non static data member or call non)static method directly.+. this and super cannot be used in static conte#t.

'.   class A9+. int aB;H ==non static .;. public static void main0-tring args?@(9>. -ystem.out.println0a(. <

. <

Output:'ompile $ime rror

Que)why main method is static?

Ans( because object is not re2uired to call static method if it were non)static method, jvm create

object first then call main0( method that will lead the problem of e#tra memory allocation.

3)static block• Is used to initiali*e the static data member.

• It is e#ecuted before main method at the time of classloading.

Example of static bloc% '.   class A9+.

. static9-ystem.out.println0Estatic bloc! is invo!edE(<;.>. public static void main0-tring args?@(9. -ystem.out.println0Eello mainE(. <F. <

Output:static loc! is ino!ed

  *ello main

Que)Can we execute a program without main() method?

Ans(Mes, one of the way is static bloc! but in previous version of &3J not in &3J '..

'.   class A9+. static9. -ystem.out.println0Estatic bloc! is invo!edE(;. -ystem.e#it0H(>. <. <

Output:static loc! is ino!ed (i+ not ,&K-)

this keyword

Page 17: Java Notes important

7/24/2019 Java Notes important

http://slidepdf.com/reader/full/java-notes-important 17/36

1here can be a lot of usage of this keyword. In java, this is a reference variable that refers to

the current object.

Usage of this keyword

ere is given the usage of this !eyword.

'. this !eyword can be used to refer current class instance variable.

+. this0( can be used to invo!e current class constructor.. this !eyword can be used to invo!e current class method 0implicitly(;. this can be passed as an argument in the method call.>. this can be passed as argument in the constructor call.

. this !eyword can also be used to return the current class instance.

)uggestion#If you are beginner to java, loo!up only two usage of this !eyword.

1) The this keyword can be used to refer current class instance

variable.

If there is ambiguity between the instance variable and parameter, this !eyword resolves the

problem of ambiguity.

Understanding the problem without this keyword

Let%s understand the problem if we don%t use this !eyword by the e#ample given below:

'.   class student9+. int id

. -tring name;.>. student0int id,-tring name(9. id B id. name B nameF. <

G. void display0(9-ystem.out.println0idDE EDname(<'H.

''. public static void main0-tring args?@(9

'+. student s' B new student0''',EJaranE(

'. student s+ B new student0+',EAryanE(

';. s'.display0('>. s+.display0('. <'. <

Output:0 null

  0 null

In the above e#ample, parameter 0formal arguments( and instance variables are same that is

why we are using this !eyword to distinguish between local variable and instance variable.

Solution of the above problem by this keyword

'.  ==e#ample of this !eyword 

Page 18: Java Notes important

7/24/2019 Java Notes important

http://slidepdf.com/reader/full/java-notes-important 18/36

+.   class -tudent9

. int id;. -tring name

>.. student0int id,-tring name(9. this.id B idF. this.name B nameG. <

'H. void display0(9-ystem.out.println0idDE EDname(<''. public static void main0-tring args?@(9

'+. -tudent s' B new -tudent0''',EJaranE(

'. -tudent s+ B new -tudent0+++,EAryanE(

';. s'.display0(

'>. s+.display0('. <'. <

Output111 Karan

  222 Aryan

If local variables0formal arguments( and instance variables are different, there is no need to use

this !eyword li!e in the following program:

Program where this keyword is not required

'.   class -tudent9

+. int id. -tring name;.>. student0int i,-tring n(9. id B i. name B nF. <

G. void display0(9-ystem.out.println0idDE EDname(<'H. public static void main0-tring args?@(9

''. -tudent e' B new -tudent0''',E!aranE(

'+. -tudent e+ B new -tudent0+++,EAryanE(

'. e'.display0(

';. e+.display0('>. <'. <

Output:111 Karan

  222 Aryan

Page 19: Java Notes important

7/24/2019 Java Notes important

http://slidepdf.com/reader/full/java-notes-important 19/36

2) this() can be used to invoked current class constructor.

1he this0( constructor call can be used to invo!e the current class constructor 0constructor chaining(.

1his approach is better if you have many constructors in the class and want to reuse that

constructor.

'.  ==Program of this0( constructor call 0constructor chaining( +.

.   class -tudent9;. int id>. -tring name. -tudent 0(9-ystem.out.println0Edefault constructor is invo!edE(<.F. -tudent0int id,-tring name(9G. this 0( ==it is used to invo!ed current class constructor. 'H. this.id B id

''. this.name B name'+. <

'. void display0(9-ystem.out.println0idDE EDname(<';.'>. public static void main0-tring args?@(9

'. -tudent e' B new -tudent0''',E!aranE(

'. -tudent e+ B new -tudent0+++,EAryanE(

'F. e'.display0('G. e+.display0(+H. <

+'. <

Output:

  de+ault constructor is ino!ed

  de+ault constructor is ino!ed

  111 Karan

  222 Aryan

Where to use this() constructor call?

1he this0( constructor call should be used to reuse the constructor in the constructor. It maintains

the chain between the constructors i.e. it is used for constructor chaining. Let%s see the e#ample

given below that displays the actual use of this !eyword.

'.   class -tudent9

+. int id

. -tring name;. -tring city>.. -tudent0int id,-tring name(9. this.id B idF. this.name B nameG. <'H. -tudent0int id,-tring name,-tring city(9''. this0id,name( ==now no need to initiali*e id and name 

'+. this.cityBcity'. <

';. void display0(9-ystem.out.println0idDE EDnameDE EDcity(<

'>.'. public static void main0-tring args?@(9

'. -tudent e' B new -tudent0''',E!aranE(

'F. -tudent e+ B new -tudent0+++,EAryanE,EdelhiE(

'G. e'.display0(

Page 20: Java Notes important

7/24/2019 Java Notes important

http://slidepdf.com/reader/full/java-notes-important 20/36

+H. e+.display0(

+'. <++. <

Output:111 Karan null

  222 Aryan delhi

Rule: Call to this( must be the first statement in constructor.

'.   class -tudent9

+. int id. -tring name;. -tudent 0(9-ystem.out.println0Edefault constructor is invo!edE(<>.. -tudent0int id,-tring name(9. id B idF. name B nameG. this 0( ==must be the first statement 

'H. <

''. void display0(9-ystem.out.println0idDE EDname(<'+.'. public static void main0-tring args?@(9

';. -tudent e' B new -tudent0''',E!aranE(

'>. -tudent e+ B new -tudent0+++,EAryanE(

'. e'.display0('. e+.display0('F. <'G. <

Output:'ompile $ime rror

3)The this keyword can be used to invoke current class method(implicitly).

Mou may invo!e the method of the current class by using the this !eyword. If you don%t use the

this !eyword, compiler automatically adds this !eyword while invo!ing the method. Let%s see the

e#ample

'.   class -9+. void m0(9. -ystem.out.println0Emethod is invo!edE(;. <>. void n0(9. this.m0( ==no need because compiler does it for you. 

. <F. void p0(9

G. n0( ==complier will add this to invo!e n0( method as this.n0( 'H. <

Page 21: Java Notes important

7/24/2019 Java Notes important

http://slidepdf.com/reader/full/java-notes-important 21/36

''. public static void main0-tring args?@(9

'+. - s' B new -0('. s'.p0(

';. <'>. <

Output:method is ino!ed

4) this keyword can be passed as an argument in the method.1he this !eyword can also be passed as an argument in the method. It is mainly used in the

event handling. Let%s see the e#ample:

'.   class -9

+. void m0- obj(9. -ystem.out.println0Emethod is invo!edE(;. <>. void p0(9. m0this(. <F.

G. public static void main0-tring args?@(9'H. - s' B new -0(''. s'.p0(

'+. <'. <

Output:method is ino!ed

Application of this that can be passed as an argument:

In event handling 0or( in a situation where we have to provide reference of a class to another

one.

5) The this keyword can be passed as argument in the constructor

call.

$e can pass the this !eyword in the constructor also. It is useful if we have to use one object in

multiple classes. Let%s see the e#ample:

'.   class /9+. A obj. /0A obj(9;. this.objBobj

>. <. void display0(9

. -ystem.out.println0obj.data( ==using data member of A class F. <

G. <'H.

''.   class A9

'+. int dataB'H

'. A0(9

';. / bBnew /0this('>. b.display0(

'. <'. public static void main0-tring args?@(9'F. A aBnew A0('G. <+H. <

Output:10

Page 22: Java Notes important

7/24/2019 Java Notes important

http://slidepdf.com/reader/full/java-notes-important 22/36

6) The this keyword can be used to return current class instance.

$e can return the this !eyword as an statement from the method. In such case, return type of

the method must be the class type 0non)primitive(. Let%s see the e#ample:

Syntax of this that can be returned as a statement'. return7type method7name0(9+.   return this. <

Example of this %ey$ord that you return as a

statement from the method'.   class A9

+. A getA0(9.   return this

;. <>.   void msg0(9-ystem.out.println0Eello javaE(<

. <

.F.   class 1est9G.   public static void main0-tring args?@(9'H.   new A0(.getA0(.msg0(''. <'+. <

Output:*ello aa

Proving this keyword

Let%s prove that this !eyword refers to the current class instance variable. In this program, we

are printing the reference variable and this, output of both variables are same.'.   class A9+.   void m0(9. -ystem.out.println0this( ==prints same reference I3 ;. <

>..   public static void main0-tring args?@(9

. A objBnew A0(F. -ystem.out.println0obj( ==prints the reference I3 

G.'H. obj.m0(''. <

'+. <Output:A/13dc02

  A/13dc02

Inheritance in Java

*nheritance is a mechanism in which one object ac2uires all the properties and behaviours of

parent object.

Page 23: Java Notes important

7/24/2019 Java Notes important

http://slidepdf.com/reader/full/java-notes-important 23/36

1he idea behind inheritance is that you can create new classes that are built upon e#isting classes.

$hen you inherit from an e#isting class, you reuse 0or inherit( methods and fields, and you add new

methods and fields to adapt your new class to new situations.

Inheritance represents the *)-( relationship.

Why use Inheritance?• "or 4ethod Overriding 0-o 5untime Polymorphism(.

• "or Code 5eusability.

Syntax of Inheritance'.   class -ubclass)name e'tends -uperclass)name

+. 9.  ==methods and fields 

;. <

1he !eyword e#tends indicates that you are ma!ing a new class that derives from an e#isting

class. In the terminology of &ava, a class that is inherited is called a superclass. 1he new class is

called a subclass.

&nderstanding the simple example of inheritance

As displayed in the above figure, Programmer is the subclass and mployee is the superclass.

5elationship between two classes is Programmer *)-( &mployee.It means that Programmer is a

type of mployee.

'.   class mployee9+. float salaryB;HHHH. <;.

>.   class Programmer e'tends mployee9. int bonusB'HHHH

.F. public static void main0-tring args?@(9

G. Programmer pBnew Programmer0('H. -ystem.out.println0EProgrammer salary is:EDp.salary(''. -ystem.out.println0E/onus of Programmer is:EDp.bonus('+. <'. <

Output:rorammer salary is:40000.0

  "onus o+ prorammer is:10000

 

In the above e#ample,Programmer object can access the field of own class as well as of mployee

class i.e. code reusability.

Page 24: Java Notes important

7/24/2019 Java Notes important

http://slidepdf.com/reader/full/java-notes-important 24/36

Types of Inheritance

On the basis of class, there can be three types of inheritance: single, multilevel and hierarchical.

4ultiple and ybrid is supported through interface only. $e will learn about interfaces later.

Multiple inheritance is not supported in java in case of class.

$hen a class e#tends multiple classes i.e. !nown as multiple inheritance. "or #ample:

Que) Why multiple inheritance is not supported in java?• 1o reduce the comple#ity and simplify the language, multiple inheritance is not supported in

 java. "or e#ample:'.   class A9+.   void msg0(9-ystem.out.println0EelloE(<. <

;.>.   class /9

.   void msg0(9-ystem.out.println0E$elcomeE(<

. <F.G.   class C e'tends A,/9 ==suppose if it were 'H.''. Public -tatic void main0-tring args?@(9'+. C objBnew C0('. obj.msg0( ==Now which msg0( method would be invo!ed 

';. <'>. <

Method Overriding in Java

Page 25: Java Notes important

7/24/2019 Java Notes important

http://slidepdf.com/reader/full/java-notes-important 25/36

If subclass 0child class( has the same method as declared in the parent class, it is !nown as method

overriding.

In other words, If subclass provides the specific implementation of the method that has been

provided by one of its parent class, it is !nown as 4ethod Overriding.

Advantage of Java Method Overriding• 4ethod Overriding is used to provide specific implementation of a method that is already

provided by its super class.

• 4ethod Overriding is used for 5untime Polymorphism

Rules for Method Overriding

'. method must have same name as in the parent class

+. method must have same parameter as in the parent class.

. must be I-)A relationship 0inheritance(.

Understanding the problem without method overriding

Let%s understand the problem that we may face in the program if we don%t use method overriding.

'. class ehicle9+. void run0(9-ystem.out.println0Eehicle is runningE(<

. <

;. class /i!e e'tends ehicle9>.. public static void main0-tring args?@(9

. /i!e obj B new /i!e0(F. obj.run0(G. <'H. <

Output:ehicle is runnin

Problem is that I have to provide a specific implementation of run0( method in subclass that is why

we use method overriding.

Example of method overriding

In this e#ample, we have defined the run method in the subclass as defined in the parent class but it

has some specific implementation. 1he name and parameter of the method is same and there is I-)

A relationship between the classes, so there is method overriding.

'.   class ehicle9

+.   void run0(9-ystem.out.println0Eehicle is runningE(<. <

;.   class /i!e e'tends ehicle9>.   void run0(9-ystem.out.println0E/i!e is running safelyE(<

..   public static void main0-tring args?@(9

Page 26: Java Notes important

7/24/2019 Java Notes important

http://slidepdf.com/reader/full/java-notes-important 26/36

F. /i!e obj B new /i!e0(

G. obj.run0('H. <

Output:"i!e is runnin sa+ely

Real example of Java Method OverridingConsider a scenario, /an! is a class that provides functionality to get rate of interest. /ut, rate of

interest varies according to ban!s. "or e#ample, -/I, ICICI and AI- ban!s could provide FQ, Q

and GQ rate of interest.

'.   class /an!9

+.   int get5ateOfInterest0(9return H<

. <;.>.   class -/I e'tends /an!9

.   int get5ateOfInterest0(9return F<

. <F.G.   class ICICI e'tends /an!9

'H.   int get5ateOfInterest0(9return <''. <'+.   class AI- e'tends /an!9

'.   int get5ateOfInterest0(9return G<

';. <'>.

'.   class 1est9'.   public static void main0-tring args?@(9'F. -/I sBnew -/I0('G. ICICI iBnew ICICI0(+H. AI- aBnew AI-0(+'. -ystem.out.println0E-/I 5ate of Interest: EDs.get5ateOfInterest0((

++. -ystem.out.println0EICICI 5ate of Interest: EDi.get5ateOfInterest0((+. -ystem.out.println0EAI- 5ate of Interest: EDa.get5ateOfInterest0((

+;. <+>. <

Output:

%"# ate o+ #nterest:

#'#'# ate o+ #nterest: -

A6#% ate o+ #nterest:

Can we override static method?No, static method cannot be overridden. It can be proved by runtime polymorphism so we will

learn it later.

Page 27: Java Notes important

7/24/2019 Java Notes important

http://slidepdf.com/reader/full/java-notes-important 27/36

Why we cannot override static method?

because static method is bound with class whereas instance method is bound with object. -tatic

belongs to class area and instance belongs to heap area.

Can we override java main method?No, because main is a static method.

What is the difference between method Overloading and Method Overriding?

1here are three basic differences between the method overloading and method overriding. 1hey are

as follows:

%ethod Overloading %ethod Overriding

'( 4ethod overloading is used to

increase the readability of the

program.

4ethod overriding is used to provide the specific

implementation of the method that is already provided by its

super class.

+( method overloading is performed

within a class.

4ethod overriding occurs in two classes that have I-)A

relationship.

( In case of method overloading

parameter must be different.

In case of method overriding parameter must be same.

super keyword

1he super is a reference variable that is used to refer immediate parent class object.

$henever you create the instance of subclass, an instance of parent class is created implicitly i.e.

referred by super reference variable.

Usage of super Keyword

'. super is used to refer immediate parent class instance variable.

+. super0( is used to invo!e immediate parent class constructor.

. super is used to invo!e immediate parent class method.

1) super is used to refer immediate parent class instance variable.Problem without super keyword 

Page 28: Java Notes important

7/24/2019 Java Notes important

http://slidepdf.com/reader/full/java-notes-important 28/36

'.   class ehicle9

+. int speedB>H. <

;.>.   class /i!e e'tends ehicle9. int speedB'HH.F. void display0(9

G. -ystem.out.println0speed( ==will print speed of /i!e'H. <''. public static void main0-tring args?@(9

'+. /i!e bBnew /i!e0('. b.display0(

';.'>. <'. <

Output:100

In the above e#ample ehicle and /i!e both class have a common property speed. Instance

variable of current class is refered by instance bydefault, but I have to refer parent class instance

variable that is why we use super !eyword to distinguish between parent class instance variable

and current class instance variable.

Solution by super keyword 

'.  ==e#ample of super !eyword +..   class ehicle9;. int speedB>H>. <.

.   class /i!e e'tends ehicle9F. int speedB'HH

G.'H. void display0(9''. -ystem.out.println0super.speed( ==will print speed of ehicle now '+. <'. public static void main0-tring args?@(9';. /i!e bBnew /i!e0('>. b.display0('.

'. <'F. <

Output:50

2) super is used to invoke parent class constructor.

1he super !eyword can also be used to invo!e the parent class constructor as given below:

'.   class ehicle9+. ehicle0(9-ystem.out.println0Eehicle is createdE(<. <;.

>.   class /i!e e'tends ehicle9. /i!e0(9

. super0( ==will invo!e parent class constructor F. -ystem.out.println0E/i!e is createdE(

G. <'H. public static void main0-tring args?@(9''. /i!e bBnew /i!e0(

Page 29: Java Notes important

7/24/2019 Java Notes important

http://slidepdf.com/reader/full/java-notes-important 29/36

'+.

'. <';. <

Output:ehicle is created

  "i!e is created

super( is added in each class constructor automatically by compiler.

As we !now well that default constructor is provided by compiler automatically but it also adds

super0( for the first statement.If you are creating your own constructor and you don%t have either

this0( or super0( as the first statement, compiler will provide super0( as the first statement of the

constructor.

Another example of super keyword where super() is provided by the compiler implicitly.

'.   class ehicle9+. ehicle0(9-ystem.out.println0Eehicle is createdE(<. <;.

>.   class /i!e e'tends ehicle9. int speed

. /i!e0int speed(9F. this.speedBspeedG. -ystem.out.println0speed('H. <''. public static void main0-tring args?@(9'+. /i!e bBnew /i!e0'H(

'. <';. <

Output:ehicle is created

  10

3) super can be used to invoke parent class method.

1he super !eyword can also be used to invo!e parent class method. It should be used in case

subclass contains the same method as parent class as in the e#ample given below:

'.   class Person9+.   void message0(9-ystem.out.println0EwelcomeE(<

. <;.

>.   class -tudent e'tends Person9.   void message0(9-ystem.out.println0Ewelcome to javaE(<

Page 30: Java Notes important

7/24/2019 Java Notes important

http://slidepdf.com/reader/full/java-notes-important 30/36

.

F.   void display0(9G. message0( ==will invo!e current class message0( method 

'H.   super.message0( ==will invo!e parent class message0( method ''. <'+.'.   public static void main0-tring args?@(9';. -tudent sBnew -tudent0(

'>. s.display0('. <'. <

Output:7elcome to aa

  7elcome

In the above e#ample -tudent and Person both classes have message0( method if we call

message0( method from -tudent class, it will call the message0( method of -tudent class not of

Person class because priority is given to local.

In case there is no method in subclass as parent, there is no need to use super. In the e#ample

given below message0( method is invo!ed from -tudent class but -tudent class does not have

message0( method, so you can directly call message0( method.

Program in case super is not required'.   class Person9+.   void message0(9-ystem.out.println0EwelcomeE(<. <;.>.   class -tudent e'tends Person9

..   void display0(9

F. message0( ==will invo!e parent class message0( method G. <

'H.''.   public static void main0-tring args?@(9'+. -tudent sBnew -tudent0('. s.display0(';. <'>. <

Output: 7elcome

Final Keyword In Java

1he final keyword in java is used to restrict the user. 1he final !eyword can be used in many

conte#t. "inal can be:

'. variable

+. method

. class

Page 31: Java Notes important

7/24/2019 Java Notes important

http://slidepdf.com/reader/full/java-notes-important 31/36

1he final !eyword can be applied with the variables, a final variable that have no value it is called

blan! final variable or uninitiali*ed final variable. It can be initiali*ed in the constructor only. 1he

blan! final variable can be static also which will be initiali*ed in the static bloc! only. $e will have

detailed learning of these. Let%s first learn the basics of final !eyword.

1) final variableIf you ma!e any variable as final, you cannot change the value of final variable0It will be constant(.

Example of 'nal variable

1here is a final variable speedlimit, we are going to change the value of this variable, but It can%t be

changed because final variable once assigned a value can never be changed.

'.   class /i!e9+. final int speedlimitBGH ==final variable . void run0(9;. speedlimitB;HH>. <. public static void main0-tring args?@(9. /i!e objBnew  /i!e0(F. obj.run0(

G. <'H. < ==end of class 

Output:'ompile $ime rror

2) final methodIf you ma!e any method as final, you cannot override it.

Example of 'nal method'.   class /i!e9

+. final void run0(9-ystem.out.println0ErunningE(<. <;.>.   class onda e'tends /i!e9

. void run0(9-ystem.out.println0Erunning safely with 'HH!mphE(<

.

F. public static void main0-tring args?@(9G. onda hondaB new onda0('H. honda.run0(''. <'+. <

Output:'ompile $ime rror

Page 32: Java Notes important

7/24/2019 Java Notes important

http://slidepdf.com/reader/full/java-notes-important 32/36

3) final classIf you ma!e any class as final, you cannot e#tend it.

Example of 'nal class'.   final class /i!e9<+.

.   class onda e'tends /i!e9

;. void run0(9-ystem.out.println0Erunning safely with 'HH!mphE(<>.. public static void main0-tring args?@(9. onda hondaB new onda0(F. honda.run0(G. <'H. <

Output:'ompile $ime rror

Q) Is final method inherited?Ans( Mes, final method is inherited but you cannot override it. "or #ample:

'.   class /i!e9

+. final void run0(9-ystem.out.println0Erunning...E(<. <;.   class onda e'tends /i!e9

>. public static void main0-tring args?@(9. new onda0(.run0(

. <F. <

Output:runnin...

Q) What is blank or uninitialized final variable?

A final variable that is not initiali*ed at the time of declaration is !nown as blan! final variable.

If you want to create a variable that is initiali*ed at the time of creating object and once initiali*ed

may not be changed, it is useful. "or e#ample PAN CA53 number of an employee.

It can be initiali*ed only in constructor.

Example of blan% 'nal variable'.   class -tudent9+.   int id. -tring name;.   final -tring PAN7CA537NR4/5>. .... <

Que) Can we initialize blank final variable?

Mes, but only in constructor. "or e#ample:

'.   class /i!e9

+. final int speedlimit ==blan! final variable .

Page 33: Java Notes important

7/24/2019 Java Notes important

http://slidepdf.com/reader/full/java-notes-important 33/36

;. /i!e0(9

>. speedlimitBH. -ystem.out.println0speedlimit(

. <F.G. public static void main0-tring args?@(9'H. new /i!e0(''. <

'+. <Output:-0

static blank final variable

A static final variable that is not initiali*ed at the time of declaration is !nown as static blan! final

variable. It can be initiali*ed only in static bloc!.

Example of static blan% 'nal variable'.   class A9

+. static final int data ==static blan! final variable . static9 dataB>H<

;. public static void main0-tring args?@(9>. -ystem.out.println0A.data(. <. <

Q) What is final parameter?

If you declare any parameter as final, you cannot change the value of it.

'.   class /i!e9+. int cube0final int n(9

. nBnD+ ==can%t be changed as n is final ;. nKnKn>. <. public static void main0-tring args?@(9. /i!e bBnew /i!e0(F. b.cube0>(G. <'H. <

Output:'ompile $ime rror

Q) Can we declare a constructor final?

No, because constructor is never inherited.

Runtime Polymorphism in Java

+untime polymorphism or ,ynamic %ethod ,ispatchis a process in which a call to an

overridden method is resolved at runtime rather than compile)time.

In this process, an overridden method is called through the reference variable of a superclass. 1he

determination of the method to be called is based on the object being referred to by the reference

variable.

Page 34: Java Notes important

7/24/2019 Java Notes important

http://slidepdf.com/reader/full/java-notes-important 34/36

Let%s first understand the upcasting before 5untime Polymorphism.

Upcasting

$hen reference variable of Parent class refers to the object of Child class, it is !nown as upcasting.

"or e#ample:

'.   class A9<+.   class / e'tends A9<'. A aBnew /0( ==upcasting 

Example of (untime #olymorphism

In this e#ample, we are creating two classes /i!e and -plendar. -plendar class e#tends /i!e class

and overrides its run0( method. $e are calling the run method by the reference variable of Parent

class. -ince it refers to the subclass object and subclass method overrides the Parent class method,

subclass method is invo!ed at runtime.

-ince method invocation is determined by the &4 not compiler, it is !nown as runtime

polymorphism.

'.   class /i!e9

+. void run0(9-ystem.out.println0ErunningE(<

. <;.   class -plender e'tends /i!e9>. void run0(9-ystem.out.println0Erunning safely with H!mE(<.. public static void main0-tring args?@(9F. /i!e b B new -plender0( ==upcasting G. b.run0('H. <''. <

Output:runnin sa+ely 7ith 80!m.

Real example of Java Runtime PolymorphismConsider a scenario, /an! is a class that provides method to get the rate of interest. /ut, rate of

interest may differ according to ban!s. "or e#ample, -/I, ICICI and AI- ban!s could provide FQ,

Q and GQ rate of interest.

Page 35: Java Notes important

7/24/2019 Java Notes important

http://slidepdf.com/reader/full/java-notes-important 35/36

Note: It is also given in method overriding but there was no upcasting.

'.   class /an!9

+.   int get5ateOfInterest0(9return H<

. <;.>.   class -/I e'tends /an!9

.   int get5ateOfInterest0(9return F<. <F.G.   class ICICI e'tends /an!9

'H.   int get5ateOfInterest0(9return <

''. <

'+.   class AI- e'tends /an!9

'.   int get5ateOfInterest0(9return G<

';. <

'>.'.   class 1est9

'.   public static void main0-tring args?@(9

'F. /an! b'Bnew -/I0('G. /an! b+Bnew ICICI0(+H. /an! bBnew AI-0(+'. -ystem.out.println0E-/I 5ate of Interest: EDb'.get5ateOfInterest0((++. -ystem.out.println0EICICI 5ate of Interest: EDb+.get5ateOfInterest0((+. -ystem.out.println0EAI- 5ate of Interest: EDb.get5ateOfInterest0((+;. <

+>. <

Output:

%"# ate o+ #nterest:

#'#'# ate o+ #nterest: -

A6#% ate o+ #nterest:

Runtime Polymorphism with data member

4ethod is overridden not the datamembers, so runtime polymorphism can%t be achieved by data

members.

In the e#ample given below, both the classes have a datamember speedlimit, we are accessing

the datamember by the reference variable of Parent class which refers to the subclass object.

-ince we are accessing the datamember which is not overridden, hence it will access thedatamember of Parent class always.

Rule: Runtime polymorphism can!t be achieved by data members.

'.   class /i!e9

+. int speedlimitBGH

. <;.   class onda e'tends /i!e9

>. int speedlimitB'>H

.

. public static void main0-tring args?@(9F. /i!e objBnew onda0(G. -ystem.out.println0obj.speedlimit( ==GH 'H. <

Page 36: Java Notes important

7/24/2019 Java Notes important

http://slidepdf.com/reader/full/java-notes-important 36/36

Output:0

Runtime Polymorphism with Multilevel Inheritance

Let%s see the simple e#ample of 5untime Polymorphism with multilevel inheritance.

'.   class Animal9+.   void eat0(9-ystem.out.println0EeatingE(<

. <;.>.   class 3og e'tends Animal9.   void eat0(9-ystem.out.println0Eeating fruitsE(<. <

F.G.   class /aby3og e'tends 3og9

'H.   void eat0(9-ystem.out.println0Edrin!ing mil!E(<''.'+.   public static void main0-tring args?@(9'. Animal a',a+,a';. a'Bnew Animal0(

'>. a+Bnew 3og0('. aBnew /aby3og0('.

'F. a'.eat0('G. a+.eat0(

+H. a.eat0(+'. <

++. <

Output: eatin

  eatin +ruits

  drin!in 9il!

Try for Output'.   class Animal9+.   void eat0(9-ystem.out.println0Eanimal is eating...E(<. <;.>.   class 3og e'tends Animal9.   void eat0(9-ystem.out.println0Edog is eating...E(<. <

F.G.   class /aby3og e'tends 3og9

'H.   public static void main0-tring args?@(9''. Animal aBnew /aby3og0(

'+. a.eat0('. <<

Output: &o is eatin

-ince, /aby3og is not overriding the eat0( method, so eat0( method of 3og class is invo!ed.