HomeWork02 Solution
HomeWork02 Solution
private int t;
//
//
//
//
Balance
Balance
Balance
Balance
is
is
is
is
0
5000
2500
2750
b=2750
On occasion, you will need to carry out the opposite conversion, from a superclass reference to a
subclass reference (also called downcasting). For example, you may have a variable of type
Object, and you know that it actually holds a BankAccount reference. In that case, you can use
an explicit cast to convert the type:
BankAccount anAccount = (BankAccount) anObject;
However, this cast is somewhat dangerous. If you are wrong, and anObject actually refers to an
object of an unrelated type, then a run-time exception is thrown.
Person
Employee
Student
Instructor
Classroom
Object
Object
Person
Student
Classroom
Employee
Instructor
package hw2.p10_4;
public class Student extends Person {
private String major;
/**
* Constructs a Student object.
* @param name
* @param birthYear
* @param major
*/
public Student(String name, int birthYear, String major) {
super(name, birthYear);
this.major = major;
}
/**
* @return Returns the major.
*/
public String getMajor() {
return major;
}
/**
* Returns a string representation of the object.
* @see hw2.p10_4.Person#toString()
*/
public String toString() {
}
package hw2.p10_4;
public class Instructor extends Person {
private double salary;
/**
* Constructs an Instructor object.
* @param name Name of the Instructor
* @param birthYear Year of birth
* @param salary Instructor's salary
*/
public Instructor(String name, int birthYear, double salary) {
super(name, birthYear);
this.salary = salary;
}
/**
* @return Returns the salary.
*/
public double getSalary() {
return salary;
}
/**
* Returns a string representation of the object.
* @see hw2.p10_4.Person#toString()
*/
public String toString() {
return "Instructor[super=" + super.toString() + ",salary=" + salary +
"]";
}
}
/**
* Description: test class for the Person, Student, and Instructor classes.
*
* @author Mihajlo Jovanovic
* @version 1.0 (May 28, 2008)
*/
package hw2.p10_4;
public class P10_4 {
public static void main(String[] args) {
Person person = new Person("Kelso", 1945);
Student student = new Student("John", 1977, "Internal Medicine");
Instructor instructor = new Instructor("Perry", 1956, 200000.0);
System.out.println(person);
System.out.println(student);
System.out.println(instructor);
}
}
References:
Eckel, B. (2002). Thinking in Java. In Chapter 8: Interfaces & Inner Classes.
Prentice Hall. Retrieved May 27, 2008 from
http://www.mindviewinc.com/Books/