父类和接口中同名方法和变量

父类及接口中同名变量和方法

一、父类与接口或接口之间出现同名变量(在接口中属于常量,只能用接口名.常量名调用)

  • 接口跟类同级,在实现接口和继承父类都存在相同变量时,导致子类无法抉择

  • 解决方法

    • 在子类的方法中显示表明要输出的变量是父类还是接口的变量。(super/接口名.变量名
  • 示例:

interface A{
    int i = 0;
}
class B{
    int i=10;
}
interface A2{
    int i = 100;
}
class Test extends B implements A,A2{
    public int printI(){
        //return super.i;	//父类中的i
        //return A.i;		//接口A中的i
        return A2.i;		//接口A2中的i
    }
}
public class Test01 {
    public static void main(String[] args) {
        Test t = new Test();
        System.out.println(t.printI());
    }
}

二、父类与接口中存在同名方法

  • 子类没有重写该方法,则默认会优先调用父类中的方法,不会报错
interface A{
    public void run();
}
class B{
    public void run(){
        System.out.println("B中的run()方法");
    }
}
class Test extends B implements A{
}
public class Test01 {
    public static void main(String[] args) {
        Test t = new Test();
        t.run();
    }
}
/*
输出:
B中的run()方法
*/
  • 子类重写了该方法,则相当于同时重写了父类以及接口中的方法。调用的是子类重写后的方法
interface A{
    public void run();
}
class B{
    public void run(){
        System.out.println("B中的run()方法");
    }
}
class Test extends B implements A{
    @Override
    public void run() {
        System.out.println("Test中的run()方法");
    }
}
public class Test01 {
    public static void main(String[] args) {
        Test t = new Test();
        t.run();
    }
}
/*
输出:
Test中的run()方法
*/

三、接口之间存在同名方法

  1. 参数列表+返回值 都相同:实现类只要实现一次此方法即可
  2. 参数列表相同+返回值不同:实现类无法直接实现两个方法(IDE报错),因为不满足方法重载原则
  3. 参数列表不相同:实现类可以分别实现两个方法,可以方法重载
//1.参数返回值都相同
interface A{
    public void run();
}
interface A2{
    public void run();
}
class Test implements A,A2{
    @Override
    public void run() {
        System.out.println("Test中的run()方法");
    }
}
public class Test01 {
    public static void main(String[] args) {
        Test t = new Test();
        t.run();	//Test中的run()方法
    }
}
//2.参数相同,返回值不相同
interface A{
    public void run();
}
interface A2{
    public int run();
}
class Test implements A,A2{
    @Override
    public void run() {	//无论重写哪一个接口中的方法都会报错,参数不同无法构成重载,定位不到哪个方法
    }
}
public class Test01 {
    public static void main(String[] args) {
        Test t = new Test();
        t.run();
    }
}
//3.参数列表不相同,分别重写,构成重载
interface A{
    public void run(int a);
}
interface A2{
    public int run();
}
class Test implements A,A2{
    @Override
    public int run() {
        return 0;
    }
    @Override
    public void run(int a) {
    }
}
public class Test01 {
    public static void main(String[] args) {
        Test t = new Test();
        t.run();
    }
}
  • 9
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值