1. class A { 2. protected int method1(int a, int b) { return 0; } 3. } Which two are valid in a clas

本文详细探讨了在Java中如何正确地重写父类的方法,包括可见性和返回类型的匹配要求,并给出了具体的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

QUESTION NO: 3
 
1. class A {
2. protected int method1(int a, int b) { return 0; }
3. }
Which two are valid in a class that extends class A? (Choose two)
A. public int method1(int a, int b) { return 0; }
B. private int method1(int a, int b) { return 0; }
C. private int method1(int a, long b) { return 0; }
D. public short method1(int a, int b) { return 0; }
E. static protected int method1(int a, int b) { return 0; }
publicclass B extends A{
    /**
     *@paramargs
     */
   
    //can not reduce the visibility of the inherited method from A
    //即不能够使从类A中继续来的方法的可见性降低  
    //private int method1(int a, int b) { return 0; }
   
    //This static method cannot hide the instance method from A
    //静态方法不能够隐藏继承于A的实例
    //static protected int method1(int a, int b) { return 0; }
   
    //返回类型与A中的该方法不一致
    //public short method1(int a, int b) { return 0; }
   
    /**
     *总结:类的继承中,如果要想重载父类的方法,必须要和父类中的返回类型、可见性等等都要操作一致
     *否则,程序就会报错。一定遵守子类要遵从于父类的原则
     *而我选择的答案居然是privateintmethod1staticprotectedint
     *我选择第一个的错误理由是:因为原来为保护的,如果我这里设为public,那么就扩展了其原来的可见性
     *本来原来就是对包外不可见的,现在变成对包外可见的了,所以就选择的是private
     *选择第二个的错误理由是:都是保护的,这里只是变成了静态的而已
     */
   
    //这里是写了一个重载方法,因为参数类型不一致,不会报错
    privateint method1(int a, long b) { return 0; }
   
    //可见性可以增大,但是不能够缩小,正确
    publicint method1(int a, int b) { return 0; }
   
    publicstaticvoid main(String[] args) {
       // TODO Auto-generated method stub
 
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值