Download presentation
Presentation is loading. Please wait.
1
Lecture 9_1 George Koutsogiannakis
CS 116 Lecture 9_1 George Koutsogiannakis
2
TOPIC Method Overriding Method Overloading
3
Method Overriding Sometimes the same method is used to produce two different results in two different classes i.e: Assume that method m is in super class A and it has signature: public int m(double d) { method code to produce a task} Suppose that class B is sub class of A (inherits A). As a result it has inherited the method m of A also. Suppose that class B is interested in adding code to m (and thus modify the original code) but it wants the same signature as m (same name, same returned value, same arguments). B can go ahead and modify the method m which is different than the m of the super class. This is called method overriding i.e
4
Method Overriding i.e. Class B version of m: public int m(double d1) {
int x = super.m(3.4); // the above is a call to the A class version to get its code //Add additional code here i.e. int y=(int)(d1+x); return y; }
5
Method Overriding The client class will go ahead and access m with an object of B: B b=new B(); int i= b.m(5.0);
6
Method Overloading Method overloading happens when a class decides to create a second version of a method that exists in the same class but with different list of arguments i.e. In our previous example the lass A had the method m with signature: public int m(double d) { method code to produce a task} Class A also decides that it wants to have different versions of m but this time the signature will also be affected by the fact that the list of argument is different i.e. public int m(double d, String str) { method code to produce a slightly different task} This is called method overloading (notice that both versions of m exist in the same class A)
7
Method Overloading The user of class A decides which version of m wants to use simple by indicating the arguments in m i.e. A a= new A(); int x=a.m(2.4); int y=a.m(3.4, “a string”); An good example of method overloading is the different constructors in a class!
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.