Overloading and Overriding Method
Overloading and Overriding Method
Programming
Overloading and Overriding Method
2 Overriding Versus Overloading
class B { class B {
public void p(int i) { public void p(int i) {
} }
} }
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
System.out.println (result);
System.out.println (doubleResult);
}
}
10
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
The Object Class
18
Student
One public method that is defined
# name : String
+ Student()
in the Object class is the
+ Student(s:String) toString()method.
+ getName():
String
22
Example 1:
public class Student
{ protected String name;
public Student () { }
public Student (String s) {
name = s;
}
public String getName() {
return name;
} }
Example 1: output
Student@82ba41
Example 2
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.";
}
}
26
Example 2
public class TestStudent2 {
public static void main( String args[]){
Student stu = new Student("Ana");
System.out.println (stu.toString());
}
}
Output:
• 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.
Overriding Methods in the Superclass
29