重写父类方法、创建单例对象 题目
题目
- 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;}}