0% found this document useful (0 votes)
50 views

Data Hiding

The document discusses method signatures and polymorphism in Java. It defines method signature as the name of the method followed by the argument types. Method overloading allows multiple methods with the same name but different arguments, while method overriding allows subclasses to provide specific implementations of methods declared in the parent class. The document also provides examples of method overloading based on changing argument types or number of arguments, and discusses how automatic type promotion works in overloaded methods.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views

Data Hiding

The document discusses method signatures and polymorphism in Java. It defines method signature as the name of the method followed by the argument types. Method overloading allows multiple methods with the same name but different arguments, while method overriding allows subclasses to provide specific implementations of methods declared in the parent class. The document also provides examples of method overloading based on changing argument types or number of arguments, and discusses how automatic type promotion works in overloaded methods.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

Method signature:

In java, method signature consists of name of the method followed by argument


types.

Example:

Note:

 In java return type is not part of the method signature.


 Compiler will use method signature while resolving method calls.

Ex-:

class Test {
public void m1(double d)
{
}
public void m2(int i)
{
}
public static void main(String ar[]) {
Test t=new Test();
t.m1(10.5);
t.m2(10);
t.m3(10.5); //CE
}
}
Note: - Within the same class we can't take 2 methods with the same signature
otherwise we will get compile time error.

Example:

public void m1()


{
}
public int m1()
{
return 10;
}
Output:
Compile time error
methodOne() is already defined in Test
Polymorphism in Java:-
 Polymorphism in Java is a concept by which we can perform a single action
in different ways. Polymorphism is derived from 2 Greek words: poly and
morphs. The word "poly" means many and "morphs" means forms. So
polymorphism means many forms.
 There are two types of polymorphism in Java: compile-time polymorphism
and runtime polymorphism. We can perform polymorphism in java by
method overloading and method overriding.
 If you overload a static method in Java, it is the example of compile time
polymorphism. Here, we will focus on runtime polymorphism in java.

Note:-

Same name with different forms is the concept of polymorphism.

Example 1: We can use same abs() method for int type, long type, float type etc.

Example:

1. abs(int)

2. abs(long)

3. abs(float)
Types of Polymorphism:-

There are two types of polymorphism in Java:

1. Compile-time polymorphism
2. Runtime polymorphism.

Note: We can perform polymorphism in java by method overloading and method


overriding.

3-Pillars of OOPS:-
1) Inheritance talks about reusability.

2) Polymorphism talks about flexibility.

3) Encapsulation talks about security.

Method Overloading in Java:-

If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.

 Two methods are said to be overload if and only if both having the same
name but different argument types.
 In 'C' language we can't take 2 methods with the same name and different
types.

If there is a change in argument type compulsory we should go for new method


name.

Example:

 Lack of overloading in "C" increases complexity of the programming.


 But in java we can take multiple methods with the same name and different
argument types.
Ex:-

 Having the same name and different argument types is called method
overloading.
 All these methods are considered as overloaded methods.
 Having overloading concept in java reduces complexity of the programming.
 If we have to perform only one operation, having same name of the methods
increases the readability of the program.

Example:

class Test {
public void m1() {
System.out.println("no-arg method");
}
public void m1(int i) {
System.out.println("int-arg method"); //overloaded methods
}
public void m1(double d) {
System.out.println("double-arg method");
}
public static void main(String[] args) {
Test t=new Test();
t.m1();//no-arg method
t.m1(10);//int-arg method
t.m1(10.5);//double-arg method
}
}
Conclusion: In overloading compiler is responsible to perform method resolution
(decision) based on the reference type (but not based on run time object). Hence
overloading is also considered as compile time polymorphism (or) static
polymorphism (or) early biding.

Different ways to overload the method:-

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

Note: - In Java, Method Overloading is not possible by changing the return type of
the method only.

1) Method Overloading: changing no. of arguments

We have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers.

Ex:-

We are creating static methods so that we don't need to create instance for calling
methods.
class Adder{
static int add(int a,int b){
return a+b;
}
static int add(int a,int b,int c){
return a+b+c;
}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
Output:
22
33
2) Method Overloading: changing data type of arguments

Ex:-

We have created two methods that differs in data type. The first add method
receives two integer arguments and second add method receives two double
arguments.

class Adder{
static int add(int a, int b){
return a+b;
}
static double add(double a, double b){
return a+b;
}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
Output:
22
24.9
Q) Why Method Overloading is not possible by changing the return type of
method only?

In java, method overloading is not possible by changing the return type of the
method only because of ambiguity. Let's see how ambiguity may occur:

class Adder{
static int add(int a,int b){
return a+b;
}
static double add(int a,int b){
return a+b;
}
}
class TestOverloading3{
public static void main(String[] args){
System.out.println(Adder.add(11,11));//ambiguity
}}
Output:
Compile Time Error: method add(int,int) is already defined in class Adder

System.out.println(Adder.add(11,11)); //Here, how can java determine which


sum() method should be called?

Can we overload java main() method?

Yes, by method overloading. You can have any number of main methods in a class
by method overloading. But JVM calls main() method which receives string array
as arguments only.

class TestOverloading4{

public static void main(String[] args){

System.out.println("main with String[]");

public static void main(String args){

System.out.println("main with String");

public static void main(){

System.out.println("main without args");

}
Output:

main with String[]

Automatic promotion in overloading.-

 In overloading if compiler is unable to find the method with exact match we


won't get any compile time error immediately.
 1st compiler promotes the argument to the next level and checks whether the
matched method is available or not if it is available then that method will be
considered if it is not available then compiler promotes the argument once
again to the next level. This process will be continued until all possible
promotions still if the matched method is not available then we will get
compile time error. This process is called automatic promotion in
overloading.

byte can be promoted to short, int, long, float or double. The short datatype can be
promoted to int, long, float or double. The char datatype can be promoted to
int,long,float or double and so on.

Method Overloading with TypePromotion:-

class OverloadingCalculation1{
void sum(int a,long b){
System.out.println(a+b);
}
void sum(int a,int b,int c){
System.out.println(a+b+c);
}

public static void main(String args[]){


OverloadingCalculation1 obj=new OverloadingCalculation1();
obj.sum(20,20);//now second int literal will be promoted to long
obj.sum(20,20,20);
}
}
Note: While resolving overloaded methods exact match will always get high
priority
Output:
40
60
Ex-2:-
class Test{
public void methodOne(int i)
{
System.out.println("int-arg method");
}
public void methodOne(float f) //overloaded methods
{
System.out.println("float-arg method");
}
public static void main(String[] args)
{
Test t=new Test();
//t.methodOne('a');//int-arg method
//t.methodOne(10l);//float-arg method
t.methodOne(10.5);//C.E:cannot find symbol
}
}
Method Overloading with Type Promotion if matching found:-

If there are matching type arguments in the method, type promotion is not
performed.

class OverloadingCalculation2{
void sum(int a,int b){
System.out.println("int arg method invoked");
}
void sum(long a,long b){
System.out.println("long arg method invoked");
}

public static void main(String args[]){


OverloadingCalculation2 obj=new OverloadingCalculation2();
obj.sum(20,20);//now int arg sum() method gets invoked
}
}
Output: int arg method invoked
Method Overloading with Type Promotion in case of ambiguity:-
If there are no matching type arguments in the method, and each method promotes
similar number of arguments, there will be ambiguity.

class OverloadingCalculation3{

void sum(int a,long b){

System.out.println("a method invoked");

void sum(long a,int b){

System.out.println("b method invoked");

public static void main(String args[]){

OverloadingCalculation3 obj=new OverloadingCalculation3();

obj.sum(20,20);//now ambiguity

Output:Compile Time Error

Note: One type is not de-promoted implicitly for example double cannot be
depromoted to any type implicitly.

Method Overriding in Java:-

 Whatever the Parent has by default available to the Child through


inheritance, if the Child is not satisfied with Parent class method
implementation then Child is allow to redefine that Parent class method in
Child class in its own way this process is called overriding.
Note: If subclass (child class) has the same method as declared in the parent
class, it is known as method overriding in Java.
If a subclass provides the specific implementation of the method that has
been declared by one of its parent class, it is known as method overriding
 The Parent class method which is overridden is called overridden method.
 The Child class method which is overriding is called overriding method.

Ex:-

class Parent {
public void property(){
System.out.println("cash+land+gold");
}
public void marry() {
System.out.println("Laxmi"); //overridden method
}
}
class Child extends Parent{ //overriding
public void marry() {
System.out.println("Kruthi/keerthi/Kajal/Pooja"); //overriding method
}
}
class Test {
public static void main(String[] args) {
Parent p=new Parent();
p.marry();//laxmi(parent method)
Child c=new Child();
c.marry();//Kruthi/keerthi/Kajal/Pooja (child method)
Parent p1=new Child();
p1.marry();//Kruthi/keerthi/Kajal/Pooja (child method)
}
}
Note: In overriding method resolution is always takes care by JVM based on
runtime object hence overriding is also considered as runtime polymorphism or
dynamic polymorphism or late binding.

The process of overriding method resolution is also known as dynamic method


dispatch.

Note: In overriding runtime object will play the role and reference type is dummy.

Usage of Java Method Overriding:-

 Method overriding is used to provide the specific implementation of a


method which is already provided by its superclass.
 Method overriding is used for runtime polymorphism.

Rules for Java Method Overriding:-

1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).
Ex:- Understanding the problem without method overriding

class Vehicle{
void run(){
System.out.println("Vehicle is running");
}
}
//Creating a child class
class Bike extends Vehicle{
public static void main(String args[]){
//creating an instance of child class
Bike obj = new Bike();
//calling the method with child class instance
obj.run();
}
}
Output:
Vehicle is running
Problem is that I have to provide a specific implementation of run() method
in subclass that is why we use method overriding.
Example of with method overriding:-
We have defined the run method in the subclass as defined in the parent class but it
has some specific implementation. The name and parameter of the method are the
same, and there is IS-A relationship between the classes, so there is method
overriding.

Ex:-

class Vehicle{
//defining a method
void run(){
System.out.println("Vehicle is running");
}
}
//Creating a child class
class Bike2 extends Vehicle{
//defining the same method as in the parent class
void run(){
System.out.println("Bike is running safely");
}
public static void main(String args[]){
Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}
Output:
Bike is running safely

A real example of Java Method Overriding:-


Consider a scenario where Bank is a class that provides functionality to get the rate
of interest. However, the rate of interest varies according to banks. For example,
SBI, ICICI and AXIS banks could provide 8%, 7%, and 9% rate of interest.

Ex:-
class Bank{
int getRateOfInterest(){
return 0;
}
}
//Creating child classes.
class SBI extends Bank{
int getRateOfInterest(){
return 8;
}
}
class ICICI extends Bank{
int getRateOfInterest(){
return 7;
}
}
class AXIS extends Bank{
int getRateOfInterest(){
return 9;
}
}
//Test class to create objects and call the methods
class Test2{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

Note: In overriding method names and arguments must be same. That is method
signature must be same.

4. Until 1.4 version the return types must be same but from 1.5 version onwards
covariant return types are allowed.

Note: Co-variant return type concept is applicable only for object types but not for
primitives.

5. According to this Child class method return type need not be same as Parent
class method return type its Child types also allowed.

6. Access modifier of child method must not restrictive than parent class method.

Note: While overriding we can't reduce the scope of access modifier.

Note: private < default < protected < public


class Parent {

public void m1() { }

class Child extends Parent {

protected void m1( ) { }

Output:

Compile time error :

7. Private, final and static methods cannot be overridden.

Note: Private methods are not visible in the Child classes hence overriding concept
is not applicable for private methods. Based on own requirement we can declare
the same Parent class private method in child class also. It is valid but not
overriding.

Ex: -
class Parent{
Private void m1(){
}
}
Class Child extends Parent{
Private void m1(){
}
}
Note: Parent class final methods we can't override in the Child class.
Note: Parent class non final methods we can override as final in child class. We
can override native methods in the child classes.

Example:

class Parent {
public final void m1() {
}
}
class Child extends Parent{
public void m1(){
}
}
}
Output:
Compile time error:
m1() in Child cannot override m1() in Parent; overridden method is final
Note: We should override Parent class abstract methods in Child classes to provide
implementation.

Example:

abstract class Parent {


public abstract void m1();
}
class Child extends Parent {
public void m1() {
}
}

Note: We can override a non-abstract method as abstract this approach is helpful to


stop availability of Parent method implementation to the next level child classes.

Ex:-

class Parent {

public void m1() {

}
abstract class Child extends Parent {

public abstract void m1();

Note: Synchronized, strictfp, modifiers won't keep any restrictions on overriding.

You might also like