Java Reference
In-Depth Information
Which of the following are legal statements?
a. Vehicle v = new Car();
b. Vehicle v = new SUV();
c. Car c = new SUV();
d. SUV s = new SUV();
e. SUV s = new Car();
f. Car c = new Vehicle();
Section 9.2: Interacting with the Superclass
4. Explain the difference between the this keyword and the super keyword. When should each be used?
5. For the next three problems, consider the following class:
1 // Represents a university student.
2 public class Student {
3
private String name;
4
private int age;
5
6 public Student(String name, int age) {
7 this .name = name;
8 this .age = age;
9 }
10
11 public void setAge( int age) {
12 this .age = age;
13 }
14 }
Also consider the following partial implementation of a subclass of Student to represent undergraduate students at
a university:
public class UndergraduateStudent extends Student {
private int year;
...
}
Can the code in the UndergraduateStudent class access the name and age fields it inherits from Student ? Can
it call the setAge method?
6. Write a constructor for the UndergraduateStudent class that accepts a name as a parameter and initializes the
UnderGraduateStudent 's state with that name, an age value of 18 , and a year value of 0 .
7. Write a version of the setAge method in the UndergraduateStudent class that not only sets the age but also
increments the year field's value by one.
Section 9.3: Polymorphism
8. Using the A , B , C , and D classes from this section, what is the output of the following code fragment?
public static void main(String[] args) {
A[] elements = {new B(), new D(), new A(), new C()};
Search WWH ::




Custom Search