The Object Class - Faculty Personal Homepage

advertisement
Inheritance
• Recall What Inheritance is About
• The extends Keyword
• The Object Class
• Overriding versus Overloading
• What is Actually Inherited?
• Single vs. Multiple Inheritance
• Up-Casting
Unit 01
1
Recall What Inheritance is About
• Inheritance allows a software developer to derive a new class from
an existing one. –Reusability
• The existing class is called the parent class, base class or super
class.
• The new class is called the child class, derived class or subclass.
• As the name implies, the child inherits characteristics of the parent.
• That is, the child class inherits the methods and data defined in the
parent class.
• Inheritance relationships are often shown
graphically in a class diagram, with the
arrow pointing to the parent class.
• Inheritance creates an is-a relationship,
meaning the child is a more specific
version of the parent.
Unit 01
2
The extends Keyword
•
In Java, the keyword extends is used to establish an inheritance.
1. public class Student{
2.
private String name;
3.
private int id;
4.
private double gpa;
5.
6.
public Student(int id, String name, double gpa){...}
7.
public Student(int id, double gpa){...}
8.
public String getName(){...}
9.
public int getId(){...}
10.
public double getGPA(){...}
11.
public String toString(){...}
12.
public void setGPA(double newGPA){...}
13. }
1. public class GraduateStudent extends Student{
2.
private String thesisTitle;
3.
public GraduateStudent(...){...}
4.
public String toString(){...} // overridden
5.
public void defendThesis(){...} // added
6. }
Unit 01
3
The Object Class
• A class called Object is defined in the java.lang package of the Java
standard class library.
• If a class is not explicitly defined to be the child of an existing class,
it is assumed to be the child of the Object class.
• Thus, the Object class is the ultimate parent of all classes.
• The Object class contains a few useful methods, toString, equals,
etc., which are inherited by all classes.
• The toString method in the Object class is defined to return the
name of the object's class and its location in the memory, while the
equals method determines if two references are aliases.
• Although all objects are guaranteed to have a toString and equals
methods, it is often desirable to override these methods when we
write our classes.
Unit 01
4
Overriding Methods
•
•
A child class can override a method it inherited from its super class.
The new method must have the same signature as the parent's method.
1. public class Student{
2.
private String name;
3.
private int id;
4.
private double gpa;
5.
//...
6.
public String toString(){
7.
return "ID: "+id+“ Name: "+name+“ GPA: "+gpa;
8.
}
9.
//...
10. }
1. public class GraduateStudent extends Student{
2.
private String thesisTitle;
3.
//...
4.
public String toString() { // overridden
5.
return super.toString()+“ Thesis Title: "+thesisTitle;
6.
}
7.
//...
Unit 01
8. }
5
Overloading vs Overriding
• Comparison between overloading and overriding
Overriding deals with two
methods, one in a parent class
and one in a child class with
the same signature
Overloading deals with
multiple methods in the same
class with the same name but
different signatures.
Overriding lets you define a
similar operation in different
ways for different object
types
Overloading lets you define a
similar operation in different
ways for different data
Unit 01
6
Constructors are not Inherited
•
•
•
Constructors are not inherited, even though they have public visibility.
However, the super reference can be used within the child's constructor to
call the parent's constructor.
In that case, the call to parent's constructor must be the first statement.
1.
2.
3.
4.
5.
6.
7.
8.
9.
public class GraduateStudent extends Student{
private String thesisTitle;
//...
public GraduateStudent(int id, String name, double gpa, String title){
super(id, name, gpa);
thesisTitle = title;
}
//...
}
•
If super is not used to call the parent's constructor, the compiler inserts a
call to the parent's default constructor. An error results if no such default
constructor exists.
Unit 01
7
What then is Inherited
•
Fields and Methods (non-private) are inherited but their access from
within the derived class depends on their access modifiers.
•
Private methods are not inherited. Private variables are inherited but they
cannot be accessed directly from the derived class.
•
For example, gpa cannot be accessed in the GraduateStudent class. To
access it in the derived class, we have to call getGPA() or setGPA()
•
An instance of a subclass also represents instance of its superclass.
GraduateStudent s = new GraduateStudent(202020, “Usman”, 3.7, “JavaMania”);
Unit 01
8
The protected Visibility Modifier
•
•
We saw that fields that are declared private cannot be accessed in the derived class.
We also know that it is a very bad practice to declare fields as public. So is there a
compromise? Yes, protected modifier.
1. public class Student{
2.
protected String name;
3.
protected int id;
4.
protected double gpa;
5.
//...
6. }
1. public class GraduateStudent extends Student{
2.
private String thesisTitle;
3.
//...
4.
public String toString(){
5.
return "ID: "+id+"Name: "+name+"GPA: "+gpa+"ThesisTitle: "+thesisTitle;
6.
}
7.
//...
8. }
Unit 01
9
Single vs. Multiple Inheritance
•
•
•
Multiple inheritance allows a class to be derived directly from two or more
classes, inheriting the members of all parents.
Collisions, such as the same variable name in two parents, have to be
resolved - leading to complex code.
To avoid this complexity, Java supports only single inheritance, meaning
that a derived class can have only one direct parent class.
Object
Student
GraduateStudent
defendThesis()
Unit 01
10
Class Hierarchy
• A child class of one parent can be the parent of another child,
forming class hierarchies.
• Two children of the same parent are called siblings - Example,
Faculty and Staff.
• Good class design puts all common features as high in the hierarchy
as is reasonable
Unit 01
11
Up-Casting
•
•
An object reference can refer to an object of its class, or to an object of any
class related to it by inheritance
For example, if the Employee class is used to derive a class, Faculty, then
an Employee reference can be used to point to a Faculty object.
• This assigning is called up-casting, because we are going up the
inheritance tree.
• Up-casting is considered to be a widening conversion since the
superclass represents more general type of objects than the
subclass.
Unit 01
12
Why Up-Casting
•
•
•
The advantage of up-casting is that some methods apply to a superclass and all its
subclasses.
Such a method can be designed to accept a superclass reference so that it can be called
with a superclass object or subclass object.
For example, a method that generates pay-slip for all employees may have the
following heading:
•
Now since the method is expecting Employee as argument, we can call it with an object
of MonthlyEmployee or HourlyEmployee.
1.
2.
3.
4.
5.
MonthlyEmployee secretary = new MonthlyEmployee("Al-Amir", 8000);
HourlyEmployee consultant = new HourlyEmployee("Umar", 500);
//...
generatePaySlip(secretary);
generatePaySlip(consultant);
Unit 01
13
Exercises
Write each of the following classes:
1.
A class, Person, with an instance variable, name. Write
appropriate accessor and mutator methods for the class. Also
write a toString method for the class.
2.
Employee, that extends Person, and has: two additional instance
variables, ID and payRate; and an additional method, pay, that
returns the payRate. Override the toString method accordingly.
3.
Faculty, that extends Employee, and has two additional variables;
officeHours of type String and teachingCourses, which is an array
of Courses. Each course has course code and course title. Write
appropriate accessor, mutator and toString methods for the class.
4.
TestPersons, that has two methods: void printPerson(Person p)
that prints its argument. And a main method that creates an
instance of each of the above classes and prints it using
printPerson method.
Unit 01
14
Example
class A {
String a = "A String";
String method1(){
return "method1() from class A.";
}
static String method2(){
return "method2() from class A.";
}
}
class ShadowingVsOverriding extends A {
double a = 7;
String method1(){
return "method1() from class ShadowingVsOverriding.";
}
static String method2(){
return "method2() from class ShadowingVsOverriding.";
}
Unit 01
15
Example – Cont’d
public static void main(String args[]){
//A obj = new ShadowingVsOverriding();
ShadowingVsOverriding obj = new ShadowingVsOverriding();
System.out.println(obj.a);
System.out.println(obj.method1());
System.out.println(obj.method2());
}
7.0
method1() from class ShadowingVsOverriding.
method2() from class ShadowingVsOverriding.
Press any key to continue...
Unit 01
16
Download