Overriding
First of all, let's create a superclass. This class has two methods:
profit(int year) – profit of the company which varies every year.
salary(int month) – worker salary for every month.
class Company {
double profit(int year) {
if (year >= 2000 && year <= 2013) {
double prof = Math.pow(year, 2.2);
return prof;
}
else {
return 0;
}
}
double salary(int month) {
if (month >= 1 && month <= 12) {
double sal = 1000 + month * 10;
return sal;
}
else {
return 0;
}
}
}Let's create two subclasses: Company1, Company2. Methods profit() and salary() in superclass are suitable for class Company1. But these methods aren't suitable for Company2. Therefore, they must be overridden.
class Company1 extends Company {
String name = "Adobe Systems";
}
class Company2 extends Company {
String name = "Microsoft Inc.";
double profit(int year) {
if (year >= 2000 && year <= 2013) {
double prof = Math.pow(year, 2.4);
return prof;
}
else {
return 0;
}
}
double salary(int month) {
if (month >= 1 && month <= 12) {
double sal = 980 + month * 12;
return sal;
}
else {
return 0;
}
}
}And let's create main class:
class MainC {
public static void main(String[] args) {
Company1 A = new Company1();
Company2 B = new Company2();
System.out.println(A.name + ": " + A.profit(2012) + "; " + A.salary(7));
System.out.println(B.name + ": " + B.profit(2012) + "; " + B.salary(7));
}
}Overloading
First of all, let's create a superclass. This class has two methods:
profit() – profit of the company.
salary() – worker salary.
class Company {
double profit() {
double prof = Math.pow(1000, 2.2);
return prof;
}
double salary() {
double sal = 1000 + 8 * 10;
return sal;
}
}Let's create two subclasses: Company1, Company2. Methods profit() and salary() in superclass are suitable for class Company1. But these methods aren't suitable for Company2, because profit of the company2 varies every year and worker salary varies every month. Therefore, they must be overloaded.
class Company1 extends Company {
String name = "Adobe Systems";
}
class Company2 extends Company {
String name = "Microsoft Inc.";
double profit(int year) {
if (year >= 2000 && year <= 2013) {
double prof = Math.pow(year, 2.4);
return prof;
}
else {
return 0;
}
}
double salary(int month) {
if (month >= 1 && month <= 12) {
double sal = 980 + month * 12;
return sal;
}
else {
return 0;
}
}
}And let's create main class:
class MainC {
public static void main(String[] args) {
Company1 A = new Company1();
Company2 B = new Company2();
System.out.println(A.name + ": " + A.profit() + "; " + A.salary());
System.out.println(B.name + ": " + B.profit(2012) + "; " + B.salary(7));
}
}