Page 272 - PowerPoint Presentation
P. 272
CAVITE STATE UNIVERSITY
TRECE MARTIRES CITY CAMPUS
Department of Information Technology DCIT 111 - Advanced Programming
// Java program to illustrate a method with return keyword
class Compute {
double Sum(double a, double b){
double sum = 0;
sum = a + b;
return sum;
}
}
public class TestCompute {
public static void main(String[]args){
System.out.println(new Compute().Sum(5.3, 6.3));
}
}
Constructor Overloading in Java
In Java, a constructor is just like a method but without return type. It can also be
overloaded like Java methods.
Constructor overloading in Java is a technique of having more than one constructor
with different parameter lists. They are arranged in a way that each constructor performs a
different task. They are differentiated by the compiler by the number of parameters in the list
and their types.
// Java program to demonstrate Constructor Overloading in Java
class Student {
int ID;
String Name;
int Age;
Student(int id, String name) {
ID = id;
Name = name;
}
Student(int id, String name, int age) {
ID = id;
Name = name;
Age = age;
}
void displayInformation(){
System.out.println(ID + “ “ + Name + “ “ + Age);
}
}
public class TestStudent{
public static void main(String[]args) {
Student Student1 = new Student(111, “Mark”);
Student Student2 = new Student(123, “Miguel”, 18);
Student1.displayInformation(); OUTPUT:
Student2.displayInformation();
} 111 Mark 0
123 Miguel 18
}
48