Method Overriding in Java

Similar documents
Chapter 14 Abstract Classes and Interfaces

Answer1. Features of Java

INHERITANCE Mrs. K.M. Sanghavi

Chapter 5. Inheritance

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

Questions Answer Key Questions Answer Key Questions Answer Key

Programming in Java, 2e Sachin Malhotra Saurabh Choudhary

Java Fundamentals (II)

Questions Answer Key Questions Answer Key Questions Answer Key

Lecture 5: Inheritance

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

Practice for Chapter 11

Relationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: "has a" CSE143 Sp Student.

Java Object Oriented Design. CSC207 Fall 2014

Mobile Application Development ( IT 100 ) Assignment - I

Inheritance and Polymorphism

What is Inheritance?

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

Inheritance Motivation

Relationships Between Real Things CSC 143. Common Relationship Patterns. Composition: "has a" CSC Employee. Supervisor

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Exam Duration: 2hrs and 30min Software Design

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

Abstract Classes Interfaces CSCI 201 Principles of Software Development

Abstract Classes Interfaces CSCI 201 Principles of Software Development

Inheritance, and Polymorphism.

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Relationships Between Real Things CSE 143. Common Relationship Patterns. Employee. Supervisor

Inheritance and Polymorphism

Class, Variable, Constructor, Object, Method Questions

CONSTRUCTOR & Description. String() This initializes a newly created String object so that it represents an empty character sequence.

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

Object Oriented Programming. Java-Lecture 11 Polymorphism

Data Structures (list, dictionary, tuples, sets, strings)

PROGRAMMING LANGUAGE 2

CSCI 355 Lab #2 Spring 2007

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Object-Oriented Programming (OOP) Fundamental Principles of OOP

OVERRIDING. 7/11/2015 Budditha Hettige 82

CISC 3115 TY3. C09a: Inheritance. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 9/20/2018 CUNY Brooklyn College

15CS45 : OBJECT ORIENTED CONCEPTS

Polymorphism CSCI 201 Principles of Software Development

1 Shyam sir JAVA Notes

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Computer Programming, I. Laboratory Manual. Final Exam Solution

CSE1720. General Info Continuation of Chapter 9 Read Chapter 10 for next week. Second level Third level Fourth level Fifth level

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

CS-140 Fall 2017 Test 1 Version Practice Practice for Nov. 20, Name:

24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

Chapter 1: Introduction to Computers, Programs, and Java

S.E (Computer ) (Second Semester) EXAMINATION, Time : Two Hours Maximum Marks : 50

First IS-A Relationship: Inheritance

More Relationships Between Classes

Computer Science II (20073) Week 1: Review and Inheritance

CS-202 Introduction to Object Oriented Programming

CMSC 132: Object-Oriented Programming II. Inheritance

22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

COP 3330 Final Exam Review

INHERITANCE. Spring 2019

Lecture 2: Java & Javadoc

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

Inheritance (Part 5) Odds and ends

Programming Languages and Techniques (CIS120)

Questions Answer Key Questions Answer Key Questions Answer Key

OBJECT ORIENTED PROGRAMMING. Abstract Class And Interface

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.

CS1150 Principles of Computer Science Objects and Classes

Fundamentals of Object Oriented Programming

Introduction to Programming Using Java (98-388)

CLASS DESIGN. Objectives MODULE 4

CIS 265/506 Exam1 Spring 2012 Prof. V. Matos Exam Last Name First Name:

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

CSCI 355 LAB #2 Spring 2004

CS260 Intro to Java & Android 03.Java Language Basics

ECE 122. Engineering Problem Solving with Java

CS 112 Programming 2. Lecture 06. Inheritance & Polymorphism (1) Chapter 11 Inheritance and Polymorphism

Programming Language Concepts Object-Oriented Programming. Janyl Jumadinova 28 February, 2017

Programming overview

[ L5P1] Object-Oriented Programming: Advanced Concepts

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

Inheritance. Benefits of Java s Inheritance. 1. Reusability of code 2. Code Sharing 3. Consistency in using an interface. Classes

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

Java for Programmers Course (equivalent to SL 275) 36 Contact Hours

What are the characteristics of Object Oriented programming language?

Lecture Notes Chapter #9_b Inheritance & Polymorphism

String is one of mostly used Object in Java. And this is the reason why String has unique handling in Java(String Pool). The String class represents

Java. Classes 3/3/2014. Summary: Chapters 1 to 10. Java (2)

Software Practice 1 - Inheritance and Interface Inheritance Overriding Polymorphism Abstraction Encapsulation Interfaces

1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4'

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Unit 4 - Inheritance, Packages & Interfaces

Transcription:

Method Overriding in Java Whenever same method name is existing in both base class and derived class with same types of parameters or same order of parameters is known as method Overriding. Method must have same name as in the parent class. Method must have same parameter as in the parent class.

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

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.

Program using super keyword al variable level 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(); 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();

Runtime Polymorphism or Dynamic method dispatch Dynamic method dispatch is a mechanism by which a call to an overridden method is resolved at runtime. This is how java implements runtime polymorphism. When an overridden method is called the type of object which it referred determines which version of overridden method will be called.

Example Cricekt.java Output : Indoor & outdoor Outdoor game Outdoor game 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

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 or implemented method. An abstract class is one which is containing some defined method and some undefined method. In java programming undefined methods are known as un-implemented or abstract method.

Important Points about abstract class and methods We cannot instantiate an abstract class. i.e., you are not 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 extended by some other class. Abstract method has no body and always end the declaration with a semicolon(;). An abstract class must be extended and in a same way abstract method must beoverridden.

Example of abstract class having constructor, data member, methods

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 in java. An interface can have methods and variables just like the class but the methods declared in interface are by default abstract (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 interface must implement/define all methods declared in the interface.

Interface vs Abstract Class An Interface is like having a 100% Abstract Class. Interfaces can not have non abstract Methods while abstract Classes can. A Class can implement more than one Interface while it can extend only one Class. As abstract Classes comes in the hierarchy of Classes, they can extend other Classes while Interface can only extend Interfaces. An abstract class can also have constructors and instance variables as well. An interface, however, can not provide any method definitions it can only provide method headings. Any class that implements the interface is responsible for providing the method definition/implementation.

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 to derived classes. An abstract class is also good if you want to be able to declare nonpublic members. If you think you will need to add methods in the future, then an abstract class is a better choice. Because if you add new method headings to an interface, then all of the classes that already implement that interface will have to be changed to implement the new methods. That can be quite a hassle. Inan 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.

Inheritance - Example interface 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();

Multiple Inheritance using interface interface 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 Employee Manager

Pass By Value Java uses pass by value to pass arguments to a method. There are important differences between passing a value of variables of primitive data types and passing arrays. For a parameter of a primitive type value, the actual value is passed. Changing the value of the local parameter inside the method does not affect the value of the variable outside the method. For a parameter of an array type, the value of the parameter contains a reference to an array; this reference is passed to the method. Any changes to the array that occur inside the method body will affect the original array that was passed as the argument. 16

Simple Example 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]); 17

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 does make sense because Java doesn't support pointers or pointer arithmetic. Answer to this question is simple whenever a method parameter expect object, reference of that object is passed. In reality if you pass object as method parameter in Java it passes "value of reference" or in simple term object reference or handle to Object in Java. Here reference term is entirely different than reference term used in C and C+ which directly points to memory address of variable and subject to pointer arithmetic

Example-passing object public 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 an object, and in the called method a new handle created and pointed to the same object. From the example above you can see that both p and a refer to the same object. class Car String model; //instance variable Car() //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 the object passed inside the called method. It is good practice to initialize instance variables of an object before passing object as parameter to method otherwise it will take default initial values.

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 extends Exam extends Results Sports implements 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