method overriding in java - csejavalab.files.wordpress.com · runtime polymorphism or dynamic...

20

Upload: others

Post on 10-Oct-2020

30 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Method Overriding in Java - csejavalab.files.wordpress.com · Runtime Polymorphism or Dynamic method dispatch Dynamic method dispatch is a mechanism by which a call to an overridden
Page 2: Method Overriding in Java - csejavalab.files.wordpress.com · Runtime Polymorphism or Dynamic method dispatch Dynamic method dispatch is a mechanism by which a call to an overridden

Method Overriding in Java

Whenever same method name is existing in both baseclass and derived class with same types of parametersor same order of parameters is known as methodOverriding.

Method must have same name as in the parent class.

Method must have same parameter as in the parentclass.

Page 3: Method Overriding in Java - csejavalab.files.wordpress.com · Runtime Polymorphism or Dynamic method dispatch Dynamic method dispatch is a mechanism by which a call to an overridden

class Walking{

void walk() {

System.out.println("Man walking fast");}

} class Man extends Walking {

void walk() {

System.out.println("Man walking slowly");}

} class OverridingDemo {

public static void main(String args[]) { Man obj = new Man(); obj.walk();

}}

Output :

Man walking slowly

Note:

•Whenever we are calling

overridden method using

derived class object reference

the highest priority is given to

current class (derived class).

We can see in the above

example high priority is derived

class.

•super. (super dot) can be used

to call base class overridden

method in the derived class.

super. walk()

Output :

Man walking slowly

Man walking fast

Page 4: Method Overriding in Java - csejavalab.files.wordpress.com · Runtime Polymorphism or Dynamic method dispatch Dynamic method dispatch is a mechanism by which a call to an overridden

Super Keyword Usage It is used inside a sub-class method definition to call a

method defined in the super class.

super is used to refer immediate parent class instance variable.

Only public and protected methods can be called by the super keyword

1) super.<variable_name> refers to the variable of variable of parent class.2) super() invokes the constructor of immediate parent class.3) super.<method_name> refers to the method of parent class.

Page 5: Method Overriding in Java - csejavalab.files.wordpress.com · Runtime Polymorphism or Dynamic method dispatch Dynamic method dispatch is a mechanism by which a call to an overridden

class Employee{

float salary=10000; } class HR extends Employee{

float salary=20000; void display() {System.out.println("Salary: "+super.salary);

//print base class salary} }

class Supervarible{ public static void main(String[] args) { HR obj=new HR(); obj.display(); }}

Program using super keyword al variable level

We use super keyword to

distinguish between parent or base

class instance variable and current

or derived class instance variable.

Example of super keyword at method level

class Student{

void message() {

System.out.println(“Morning Sir"); } }class Faculty extends Student{

void message() {

System.out.println("Good Morning Students");

} void display() {

message();//will invoke or call current class message() method

super.message();//will invoke or call parent class message() method } public static void main(String args[]) { Student s=new Student(); s.display(); } }

Page 6: Method Overriding in Java - csejavalab.files.wordpress.com · Runtime Polymorphism or Dynamic method dispatch Dynamic method dispatch is a mechanism by which a call to an overridden

Runtime Polymorphism or Dynamic method dispatch

Dynamic method dispatch is a mechanism by which a call to anoverridden method is resolved at runtime. This is how java implements

runtime polymorphism.

When an overridden method is called the type of object which itreferred determines which version of overridden method will be called.

Page 7: Method Overriding in Java - csejavalab.files.wordpress.com · Runtime Polymorphism or Dynamic method dispatch Dynamic method dispatch is a mechanism by which a call to an overridden

class Game

{

public void type()

{

System.out.println("Indoor & outdoor");

} }

class Cricket extends Game

{

public void type()

{

System.out.println(“Outdoor game");

}

public static void main(String[] args)

{

Game gm = new Game();

Cricket ck = new Cricket();

gm.type();

ck.type();

gm=ck; //gm refers to Cricket object

gm.type(); //calls Cricket's version of type

} }

Example

Output :

Indoor & outdoor

Outdoor game

Outdoor game

Cricekt.java

Page 8: Method Overriding in Java - csejavalab.files.wordpress.com · Runtime Polymorphism or Dynamic method dispatch Dynamic method dispatch is a mechanism by which a call to an overridden

Abstract class in Java In java programming we have two types of classes they are

Concrete class and Abstract class

A concrete class is one which is containing fully defined methods orimplemented method.

An abstract class is one which is containing some defined method andsome undefined method. In java programming undefined methods areknown as un-Implemented or abstract method.

Page 9: Method Overriding in Java - csejavalab.files.wordpress.com · Runtime Polymorphism or Dynamic method dispatch Dynamic method dispatch is a mechanism by which a call to an overridden

Important Points about abstract class and methods

We cannot instantiate an abstract class. i.e., you arenot allowed to create object of Abstract class.

Abstract method must be in a abstract class.

An abstract class has no use until unless it is extendedby some other class.

Abstract method has no body and always end thedeclaration with a semicolon(;).

An abstract class must be extended and in a same wayabstract method must be overridden.

Page 10: Method Overriding in Java - csejavalab.files.wordpress.com · Runtime Polymorphism or Dynamic method dispatch Dynamic method dispatch is a mechanism by which a call to an overridden

Example of abstract class having constructor, data member, methods

Page 11: Method Overriding in Java - csejavalab.files.wordpress.com · Runtime Polymorphism or Dynamic method dispatch Dynamic method dispatch is a mechanism by which a call to an overridden

Interfaces Interface is similar to class but not a class which is collection of

public static final variables (constants) and abstract methods.

The interface is a mechanism to achieve fully abstraction injava.

An interface can have methods and variables just like theclass but the methods declared in interface are by defaultabstract (only method signature, no body).

Also, the variables declared in an interface are public, static& final by default.

“Its like a checklist” : Class that implements an interfacemust implement/define all methods declared in theinterface.

Page 12: Method Overriding in Java - csejavalab.files.wordpress.com · Runtime Polymorphism or Dynamic method dispatch Dynamic method dispatch is a mechanism by which a call to an overridden

Interface vs Abstract Class An Interface is like having a 100% Abstract Class. Interfaces

can not have non abstract Methods while abstract Classescan. A Class can implement more than one Interface whileit can extend only one Class. As abstract Classes comes inthe hierarchy of Classes, they can extend other Classeswhile Interface can only extend Interfaces.

An abstract class can also have constructors and instancevariables as well. An interface, however, can not provideany method definitions – it can only provide methodheadings. Any class that implements the interface isresponsible for providing the methoddefinition/implementation.

Page 13: Method Overriding in Java - csejavalab.files.wordpress.com · Runtime Polymorphism or Dynamic method dispatch Dynamic method dispatch is a mechanism by which a call to an overridden

When to use abstract class and interface in Java An abstract class is good if you think you will plan on using

inheritance since it provides a common base class implementation toderived classes.

An abstract class is also good if you want to be able to declare non-public members.

If you think you will need to add methods in the future, then anabstract class is a better choice. Because if you add new methodheadings to an interface, then all of the classes that already implementthat interface will have to be changed to implement the new methods.That can be quite a hassle.

In an interface, all methods must be public. Interfaces are a good choice when you think that the API will not

change for a while. Interfaces are also good when you want to have something similar to

multiple inheritance, since you can implement multiple interfaces.

Page 14: Method Overriding in Java - csejavalab.files.wordpress.com · Runtime Polymorphism or Dynamic method dispatch Dynamic method dispatch is a mechanism by which a call to an overridden

Inheritance - Exampleinterface Person{

void run(); // abstract method} class A implements Person{public void run() {

System.out.println("Run fast"); }

public static void main(String args[]) {A obj = new A();

obj.run(); } }

Page 15: Method Overriding in Java - csejavalab.files.wordpress.com · Runtime Polymorphism or Dynamic method dispatch Dynamic method dispatch is a mechanism by which a call to an overridden

Multiple Inheritance using interfaceinterface Developer{

void disp(); } interface Manager{

void show(); }class Employee implements Developer, Manager{

public void disp() {

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

public void show() { System.out.println("How are you ?");

} public static void main(String args[]) { Employee obj=new Employee(); obj.disp(); obj.show(); } }

Developer Manager

Employee

Page 16: Method Overriding in Java - csejavalab.files.wordpress.com · Runtime Polymorphism or Dynamic method dispatch Dynamic method dispatch is a mechanism by which a call to an overridden

16

Pass By ValueJava uses pass by value to pass arguments to a method.There are important differences between passing a value ofvariables of primitive data types and passing arrays.

For a parameter of a primitive type value, the actual valueis passed. Changing the value of the local parameter insidethe method does not affect the value of the variable outsidethe method.

For a parameter of an array type, the value of theparameter contains a reference to an array; this reference ispassed to the method. Any changes to the array that occurinside the method body will affect the original array thatwas passed as the argument.

Page 17: Method Overriding in Java - csejavalab.files.wordpress.com · Runtime Polymorphism or Dynamic method dispatch Dynamic method dispatch is a mechanism by which a call to an overridden

17

public class Test {

public static void m(int number, int[] numbers) {

number = 1001; // Assign a new value to number

numbers[0] = 5555; // Assign a new value to numbers[0]

}

public static void main(String[] args) {

int x = 1; // x represents an int value

int[] y = new int[10]; // y represents an array of int values

m(x, y); // Invoke m with arguments x and y

System.out.println("x is " + x);

System.out.println("y[0] is " + y[0]);

}

}

Simple Example

Page 18: Method Overriding in Java - csejavalab.files.wordpress.com · Runtime Polymorphism or Dynamic method dispatch Dynamic method dispatch is a mechanism by which a call to an overridden

Does Java pass by value or pass by reference - Interview Question As per Java specification everything in Java is pass by

value whether its primitive value or objects and it doesmake sense because Java doesn't support pointers orpointer arithmetic.

Answer to this question is simple whenever a methodparameter expect object, reference of that object is passed.

In reality if you pass object as method parameter in Java itpasses "value of reference" or in simple term objectreference or handle to Object in Java. Here reference termis entirely different than reference term used in C and C+which directly points to memory address of variable andsubject to pointer arithmetic

Page 19: Method Overriding in Java - csejavalab.files.wordpress.com · Runtime Polymorphism or Dynamic method dispatch Dynamic method dispatch is a mechanism by which a call to an overridden

Example-passing objectpublic class ObjPass {private int value;public static void increment(ObjPass a){System.out.println(a);a.value++;}public static void main(String args[]){

ObjPass p = new ObjPass();p.value = 5;System.out.println("Before:" + p.value);increment(p);System.out.println("After: " + p.value);System.out.println(p);

}}

Here we pass exactly is a handle of anobject, and in the called method a newhandle created and pointed to the sameobject. From the example above you cansee that both p and a refer to the sameobject.

class Car{

String model; //instance variableCar() { //constructor to initialize

model="Maruthi";System.out.println("Car Model is:"+model);}void disp(Car m) {System.out.println("My Car Model is:"+m.model);

} }public class ObjPass1 {public static void main(String args[]){

Car mycar = new Car();mycar.model="Zen";mycar.disp(mycar);

} } }We can access the instance variables of theobject passed inside the called method. Itis good practice to initialize instancevariables of an object before passingobject as parameter to method otherwiseit will take default initial values.

Page 20: Method Overriding in Java - csejavalab.files.wordpress.com · Runtime Polymorphism or Dynamic method dispatch Dynamic method dispatch is a mechanism by which a call to an overridden

Exercises Modify Cricket.java file and insert a ‘chess’ class and print “Indoor

Game” using Dynamic-method-dispatch.

Write an abstract class Shape with Abstract methods: getArea(), getPerimeter() and find the area of rectangle.

Write a program to add two complex numbers using pass by object

Implement the following using inheritance.

Student Sports

Exam

Results

extends

extendsimplements

class Student{

// student no and access methods}interface Sport{

// sports grace marks (say 5 marks) and abstract methods}class Exam extends Student{

// example marks (test1 and test 2 marks) and access methods}class Results extends Exam implements Sport{

// implementation of abstract methods of Sport interface

// other methods to compute total marks = test1+test2+sports_grace_marks;

// other display or final results access methods}