EKT472: Object Oriented Programming Overloading and Overriding Method.

Slides:



Advertisements
Similar presentations
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Advertisements

Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 8 Inheritance and.
OOP: Inheritance By: Lamiaa Said.
1 Inheritance Chapter 9. 2 Module Outcomes To develop a subclass from a superclass through inheritance To invoke the superclass ’ s constructors and methods.
Class Hierarchies. Inheritance is the capability of a class to use the properties and methods of another class while adding its own functionality. An.
Java Inheritance. What is inherited A subclass inherits variables and methods from its superclass and all of its ancestors. The subclass can use these.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
OVERRIDING/OVERLOADING Srinivas. EXAM OBJECTIVES  Given a code example, determine if a method is correctly overriding or overloading another method,
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 5, page 1 Sun Certified Java 1.4 Programmer Chapter 5 Notes Gary Lance
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
Object-Oriented Programming. An object is anything that can be represented by data in a computer’s memory and manipulated by a computer program.
OOP: Encapsulation,Abstraction & Polymorphism. What is Encapsulation Described as a protective barrier that prevents the code and data being randomly.
Polymorphism. 3 main programming mechanisms that constitute OOP: 1. Encapsulation 2. Inheritance 3. Polymorphism.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and.
Object Oriented Programming
10 Polymorphism. 2 Contents Defining Polymorphism Method Overloading Method Overriding Early Binding and Late Binding Implementing Polymorphism.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
CMSC 202 Polymorphism. 10/20102 Topics Binding (early and late) Upcasting and downcasting Extensibility The final modifier with  methods  classes.
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
CS 112 Programming 2 Lecture 06 Inheritance & Polymorphism (1)
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
COMP Inheritance and Polymorphism Yi Hong June 09, 2015.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
BY:- TOPS Technologies
Comp1004: Inheritance II Polymorphism. Coming up Inheritance Reminder Overriding methods – Overriding and substitution Dynamic Binding Polymorphism –
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Inheritance.
Polymorphism in Methods
Polymorphism.
Inheritance ITI1121 Nour El Kadri.
Overriding Method.
Chapter 11 Inheritance and Polymorphism
Chapter 11 Inheritance and Polymorphism
Inheritance and Polymorphism
Continuing Chapter 11 Inheritance and Polymorphism
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
ATS Application Programming: Java Programming
Object Oriented Programming
Chapter 9 Inheritance and Polymorphism
Inheritance Basics Programming with Inheritance
Java Programming Language
Inheritance, Polymorphism, and Interfaces. Oh My
Polymorphism and access control
Advanced Java Topics Chapter 9
Week 6 Object-Oriented Programming (2): Polymorphism
CMSC 202 Polymorphism.
Chapter 9 Inheritance and Polymorphism
Computer Programming with JAVA
Chapter 11 Inheritance and Polymorphism
Java Inheritance.
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Chapter 9 Carrano Chapter 10 Small Java
Chapter 11 Inheritance and Polymorphism Part 1
Chapter 11 Inheritance and Encapsulation and Polymorphism
Programming in C# CHAPTER 5 & 6
Presentation transcript:

EKT472: Object Oriented Programming Overloading and Overriding Method

2 Overriding Versus Overloading  Do not confuse overriding a method in a derived class with overloading a method name  When a method is overridden, the new method definition given in the derived class has the exact same number and types of parameters as in the base class  When a method in a derived class has a different signature from the method in the base class, that is overloading  Note that when the derived class overloads the original method, it still inherits the original method from the base class as well

3 Overriding vs. Overloading The method p(int i) in class A overrides the same method defines in class B. The method p(int i) in class A overloads the same method defines in class B.

4 Overloading  Overloaded methods let you reuse the same method name in a class, but with different arguments (and optionally, a different return type).  Overloading a method often means you're being a little nicer to those who call your methods, because your code takes on the burden of coping with different argument types rather than forcing the caller to do conversions prior to invoking your method.

5 Overloading rules  Overloaded methods MUST change the argument list.  Overloaded methods CAN change the return type.  Overloaded methods CAN change the access modifier.  Overloaded methods CAN declare new or broader checked exceptions.  A method can be overloaded in the same class or in a subclass.

6 Legal Overloads public void changeSize(int size, String name, float pattern) { }  The following methods are legal overloads of the changeSize() method: public void changeSize(int size, String name) { } public int changeSize(int size, float pattern) { } public void changeSize(float pattern, String name){ }

7 Invoking Overloaded Methods  When a method is invoked, more than one method of the same name might exist for the object type you're invoking a method on.  For example, the Adder class might have two methods with the same name but with different argument lists, which means the method is overloaded.

8 Class Adder public class Adder { public int addThem(int x, int y) { return x + y; } // Overload the addThem method to add doubles instead of ints public double addThem(double x, double y) { return x + y; }

9 Class TestAdder public class TestAdder { public static void main (String [] args) { Adder a = new Adder(); int b = 27; int c = 3; // Which addThem is invoked? int result = a.addThem(b,c); double doubleResult = a.addThem(22.5,9.3); System.out.println (result); System.out.println (doubleResult); }

10  The first call to a.addThem(b, c) passes two ints to the method, so the first version of addThem() — the overloaded version that takes two int arguments — is called.  The second call to a.addThem(22.5, 9.3) passes two doubles to the method, so the second version of addThem() — the overloaded version that takes two double arguments—is called.

11 Invoking overloaded methods that take object references class Animal { } class Horse extends Animal { } public class UseAnimals { public void doStuff(Animal a) { System.out.println("In the Animal version"); } public void doStuff(Horse h) { System.out.println("In the Horse version"); }

12 Invoking overloaded methods that take object references public class TestUseAnimals2 { public static void main (String [] args) { UseAnimals ua = new UseAnimals(); Animal animalobj = new Animal(); Horse horseobj = new Horse(); Animal animalRefToHorse = new Horse(); ua.doStuff(animalobj); ua.doStuff(horseobj); ua.doStuff(animalRefToHorse); }

13  Lets say, one version takes an Animal and one takes a Horse (subclass of Animal).  If you pass a Horse object in the method invocation, you'll invoke the overloaded version that takes a Horse.  If you use an Animal reference to a Horse object, the compiler knows only about the Animal, so it chooses the overloaded version of the method that takes an Animal.  Even though the actual object at runtime is a Horse and not an Animal, the choice of which overloaded method to call (in other words, the signature of the method) is NOT dynamically decided at runtime.  To summarize, which overridden version of the method to call (in other words, from which class in the inheritance tree) is decided at runtime based on object type, but which overloaded version of the method to call is based on the reference type of the argument passed at compile time.

14

15

16

Overriding Method

18 The Object Class Every class in Java is descended from the java.lang.Object class. If no inheritance is specified when a class is defined, the superclass of the class is Object.

19 Declaring a Subclass A subclass extends properties and methods from the superclass. You can also: FAdd new properties FAdd new methods FOverride the methods of the superclass

20 The toString() method in Object The toString() method returns a string representation of the object. The default implementation returns a string consisting of a class name of which the object is an instance, the at sign and a number representing this object. Circle circ = new Circle(); System.out.println(circ.toString()); The code displays something like This message is not very helpful or informative. Usually you should override the toString method so that it returns a digestible string representation of the object.

21 Example 1: Object + toString(): String Student # name : String + Student() + Student(s:String) + getName(): String By default, all Java classes are subclasses of the Object class (the most general class in Java’s hierarchy). One public method that is defined in the Object class is the toString() method.

22 public class Student {protected String name; public Student () { } public Student (String s) { name = s; } public String getName() { return name; } } Example 1: public class TestStudent1 { public static void main( String args[]){ Student stu = new Student("Ana"); System.out.println (stu.toString()); }

23 Example 1: output The default implementation of toString() Returns the name of the object’s class and the address where the object is stored in the memory. Name of the object Address of the object

24 Example 2: Overriding an Inherited Method Object + toString(): String Student # name : String + Student() + Student(s:String) + getName(): String + toString():String toString() method is redefined in subclasses of Object class. Overriding toString() in a Subclass provides a customized string representation of the Object in that subclass.

25 public class Student {protected String name; public Student () { } public Student (String s) { name = s; } public String getName() { return name; } public String toString() { return "My name is " + name + " and I am a Student."; } Example 2

26 Example 2 public class TestStudent2 { public static void main( String args[]){ Student stu = new Student("Ana"); System.out.println (stu.toString()); } My name is Ana and I am a Student. Output:

27 Overriding Methods in the Superclass Any time you have a class that inherits a method from a superclass, you have the opportunity to override the method (unless, the method is marked final). The key benefit of overriding is the ability to define behavior that's specific to a particular subclass type. public class Animal { public void eat() { System.out.println("Generic Animal Eating Generically"); } class Horse extends Animal { public void eat() { System.out.println("Horse eating hay, oats, " + "and horse treats"); } public void buck() { System.out.println ("This is how I jump"); }

28 Overriding Methods in the Superclass The Animal class creator might have decided that for the purposes of polymorphism, all Animal subtypes should have an eat() method defined in a unique, specific way. Polymorphically, when someone has an Animal reference that refers not to an Animal instance, but to an Animal subclass instance, the caller should be able to invoke eat() on the Animal reference, but the actual runtime object (say, a Horse instance) will run its own specific eat() method. public class TestAnimals { public static void main (String [] args) { Animal a = new Animal(); Animal b = new Horse(); //Animal ref, but a Horse object a.eat(); // Runs the Animal version of eat() b.eat(); // Runs the Horse version of eat() }

29 Overriding Methods in the Superclass The TestAnimal2 class uses an Animal reference to invoke a method on a Horse object. Remember, the compiler will allow only methods in class Animal to be invoked when using a reference to an Animal. Can't invoke buck(); because Animal class doesn't have that method. public class TestAnimal2 { public static void main (String [] args) { Animal c = new Horse(); //Animal ref, but a Horse object c.buck(); }

30 Overriding Methods in the Superclass A subclass inherits methods from a superclass. Sometimes it is necessary for the subclass to modify the implementation of a method defined in the superclass. This is referred to as method overriding. public class Circle extends GeometricObject { // Other methods are omitted /** Override the toString method defined in GeometricObject */ public String toString() { return super.toString() + "\nradius is " + radius; }

31 Invoking a Superclass Version of an Overridden Method public class Animal2 { public void eat() { } public void printYourself() { // Useful printing code goes here } class Horse extends Animal2 { public void printYourself() { // Take advantage of Animal code, then add some more super.printYourself(); // Invoke the superclass // (Animal) code // Then do Horse-specific // print work here } The keyword super can also be used to reference a method in the superclass.

32 Dynamic Binding  A method call is bound to the correct implementation of the method at runtime by the Java Virtual Machine (JVM).  When JVM encounters a method call, it uses information about the class hierarchy to bind the method call to the correct implementation of that method.  Java’s dynamic-binding mechanism, which is also called late binding, or runtime binding, leads to what is known as polymorphism.

33 NOTE An instance method can be overridden only if it is accessible. Thus a private method cannot be overridden, because it is not accessible outside its own class.

34 A private method cannot be overridden public class TestAnimals3 { public static void main (String [] args) { Horse h = new Horse(); h.eat(); } class Animal { private void eat() { System.out.println("Generic Animal Eating Generically"); } class Horse extends Animal { } } Method eat() in the superclass can’t be inherited, because it is private. Therefore, method eat() cannot be overridden.

35 NOTE If a method defined in a subclass is private in its superclass, the two methods are completely unrelated.

36 A private method cannot be overridden public class TestAnimals2 { public static void main (String [] args) { Animal a = new Animal(); Animal b = new Horse(); //Animal ref, but a Horse object a.eat(); // Runs the Animal version of eat() b.eat(); // Runs the Horse version of eat() } class Animal { public void eat() { System.out.println("Generic Animal Eating Generically"); } class Horse extends Animal { private void eat() { // whoa! - it's private! System.out.println("Horse eating hay, oats, " + "and horse treats"); }