I have added the solutions for all labs and recommend that you study them as par
ID: 3773400 • Letter: I
Question
I have added the solutions for all labs and recommend that you study them as part of your preparation for exam tomorrow.
I had promised to give an example for overriding and overloading methods and here it is:
If class Person has a method called getInfo that returns the information for the person:
public String getInfo() {
return "Name: " + name + " Address: " + address;
}
An overriden method in Student class that extends Person, would be:
public String getInfo() {
return super.getInfo() + "ID: " + id + "GPA: + gpa;
}
Assuming name and address are Person class's fields and id and gpa are Student class's fields.
To overload a method, the parameter list in the method signature should be different.
public void add (int a, int b)
public void add(double a, double b)
public void add(int a, int b, int c)
are all overloaded methods.
Explanation / Answer
The functions
public void add (int a, int b)
public void add(double a, double b)
public void add(int a, int b, int c)
are all overloaded methods.
Here the complete program to show the implementation of overloaded methods.
OUTPUT:
Code to copy:
public class addOverloading
{
//function to add two integers
public static void add(int n1, int n2)
{
int sum;
sum=n1+n2;
System.out.println("sum of "+n1+" and "+n2+" is "+sum);
}
//function to add two double values
public static void add(double n1, double n2)
{
double sum;
sum=n1+n2;
System.out.println("sum of "+n1+" and "+n2+" is "+sum);
}
//function to add three integers
public static void add(int n1, int n2, int n3)
{
int sum;
sum=n1+n2+n3;
System.out.println("sum of "+n1+", "+n2+" and "+n3 +" is "+sum);
}
public static void main(String[] args)
{
add(5, 7); //to call function add with two integers
add(7.8, 8.7); //to call function add with two double values
add(4,9,13); //to call function add with three integers
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.