重写父类方法、创建单例对象 题目

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;
    }
    
}

  • 10
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值