題目
- JAVA27 重寫父類方法
- 分析:
- 代碼:
- JAVA28 創建單例對象
- 分析:
- 代碼:
JAVA27 重寫父類方法
描述
父類Base中定義了若干get方法,以及一個sum方法,sum方法是對一組數字的求和。請在子類 Sub 中重寫 getX() 方法,使得 sum 方法返回結果為 x*10+y
?
輸入描述:
整數
?
輸出描述:
整數的和
示例:
輸入:1 2 輸出:12
?
?
分析:
? 1.直接在子類重寫的方法中使用super關鍵字。
? 2.使用super關鍵字調用父類的getX()方法。
? 3.最后乘10,并返回。
?
代碼:
import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);while (scanner.hasNextInt()) {int x = scanner.nextInt();int y = scanner.nextInt();Sub sub = new Sub(x, y);System.out.println(sub.sum());}}}class Base {private int x;private int y;public Base(int x, int y) {this.x = x;this.y = y;}public int getX() {return x;}public final int getY() {return y;}public final int sum() {return getX() + getY();}}class Sub extends Base {public Sub(int x, int y) {super(x, y);}//write your code here......public int getX() {return super.getX()*10;}}
?
?
?
JAVA28 創建單例對象
描述
Singleton類是單例的,每次調用該類的getInstance()方法都將得到相同的實例,目前該類中這個方法尚未完成,請將其補充完整,使得main()函數中的判斷返回真(不考慮線程安全)。
?
輸入描述:
無
?
輸出描述:
true
?
分析:
? 1.題目描述的是單例模式的懶漢式,直接根據懶漢式編寫就好。
?
代碼:
public class Main {public static void main(String[] args) {Singleton s1 = Singleton.getInstance();Singleton s2 = Singleton.getInstance();System.out.println(s1 == s2);}}class Singleton {private static Singleton instance;private Singleton() {}//write your code here......public static Singleton getInstance(){if(instance == null){instance = new Singleton();}return instance;}}