SCJP題庫第025題



1. class ClassA{
2.   public int numberOfInstances;
3.   protected ClassA(int numberOfInstances){
4.     this.numberOfInstances = numberOfInstances;
5.   }
6. }
7. class ExtendedA extends ClassA{
8.   private ExtendedA(int numberOfInstances){
9.     super(numberOfInstances);
10. }
11. public static void main(String[] args){
12.   ExtendedA ext = new ExtendedA(420);
13.   System.out.print(ext.numberOfInstances);
14. }
15.}
What is the result?

A. 420 is the output
B. An exception is thrown at runtime.
C. All constructors must be declared public.
D. Constructors CANNOT use the private modifier.
E. Constructors CANNOT use the protected modifier.

Ans:A

解說:

12行建立ExtendedA 物件ext,使用建構子ExtendedA(420),這個420被複製給ExtendedA中的numberOfInstances,再呼叫super(numberOfInstances),此為父類別建構子的呼叫,此時numberOfInstances的值420被指定給父類別中numberOfInstances
main中透過ext這個物件參考來參考父類別中的numberOfInstancesok的,因其為public
ExtendedA中使用superok,因父類別建構子ClassA存取屬性是protected,子類別可以存取這個建構子。

Comments

Popular posts from this blog

Android+Google Map API v3 Geocoding(地址轉經緯度度