In: Computer Science
Write a short code segment which includes/illustrates the concepts of inheritance, overloading, and overriding in java language.
Inheritance is the concept of OOPs that one class can inherit the properties of another class. The main class is called parent class and the class which inherits this parent class is called child class. The keyword extends is used to inherit another class.
Human.java
public class Human{
private String name;
private int age;
public Human(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Human [name=" + name + ", age=" + age + "]";
}
}
Men.java
public class Men extends Human{
private String gender;
public Men(String name, int age, String gender) {
super(name, age);
this.gender = gender;
}
@Override
public String toString() {
return "Men [gender=" + gender + ", toString()=" + super.toString() + "]";
}
}
Test.java
public class Test {
public static void main (String [] args) {
Men m = new Men("John", 22, "Male");
System.out.println(m);
}
}
Overridding:
Overriding is the concept of declaring the method in the child class with the same name and same no of parameters of the parent class. The logic in the child class method will be different to the one present in the parent class
Human.java
public class Human{
private String name;
private int age;
public Human(String name, int age) {
super();
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "Human [name=" + name + ", age=" + age + "]";
}
}
Men.java
public class Men extends Human{
private String gender;
public Men(String name, int age, String gender) {
super(name, age);
this.gender = gender;
}
public int getAge() {
return super.getAge() + 1;
}
@Override
public String toString() {
return "Men [gender=" + gender + ", toString()=" + super.toString() + "]";
}
}
Test.java
public class Test {
public static void main (String [] args) {
Men m = new Men("John", 22, "Male");
System.out.println(m);
System.out.println("Call to the child class method: " + m.getAge());
}
}
Overloading:
Overloading is the concept of declaring a method with the same name multiple times in a class but with different number of parameters.
Calculation.java
public class Calculation{
public int add(int a, int b) {
return a + b;
}
public double add(double a, double b) {
return a + b;
}
}
Test.java
public class Test {
public static void main (String [] args) {
Calculation cal = new Calculation();
System.out.println(cal.add(8, 9));
System.out.println(cal.add(4.5, 6.8));
}
}