TCC102 Unit2 Tutorial2
TCC102 Unit2 Tutorial2
Tutorial 2
For example,
Full-time employee class and part-time employee
class not only inherit all the methods and data
which defined in Person class, but also can define
its own method and data. Every employee is a
person.
Inheritance Hierarchy
Person
FullTimeEmployee PartTimeEmployee
FullTimeEmployee
-payRate: double
subclass
-hoursWorked: double or
+PartTimeEmployee()
derivedclass
+PartTimeEmployee(name:String, rate:double, hours:double) or
+getPayRate(): double
+getHoursWorked(): double
child class
+setNameRateHours(name:String, rate:double, hours:double):void
+calculatePay(): double
+toString(): String
Overloading methods
If a class definition has two different methods
with same name but different parameter lists,
it is considered to be overloading
For example,
The println() method defined in the class
java.io.PrintStream.
There are 10 println() methods with different
parameter lists can be used to print primitive type
value(int, long, double) and non-primitive type
value( String, Object)
Sample
Code
Overloading methods in
constructors
public Person() {
name="unknown";
age=0;
}
public Person(String name, int age){
this.name = name;
this.age=age;
}
Overriding methods in the
Superclass
If a subclass defines a method with the same
name and parameter list as a method in
superclass, it is considered to be overriding,
and the method defined in the subclass
overrides the one defined in the superclass.
Sample
Code
override toString( ) method
toString()
method in
public class Person {
superclass
public String toString(){
return name;
}
}
public AbstractClassExample() {
x = 0;
}
}
Abstract Class Example