java面向对象接口实现_Java面向对象之接口学习(三)

一、以下代码当中test方法中打印x会报错,因为当一个类实现两个接口,这两个接口又有两个同名变量,它不知道用one当中的还是two当中的那个。因此打印x时就会产生错误提示。

package com.immoc.test;

interface one {

static int x = 11;

}

interface Two{

final int x = 22;

}

class Three {

public int x =33;

}

public class TestOne implements one,Two{

public void test() {

System.out.println(x);

}

public static void main(String[] args) {

new TestOne().test();

}

}

应该为如下:system.out.println(x)也是无法打印的。

package com.immoc.test;

interface one {

static int x = 11;

}

interface Two{

final int x = 22;

}

class Three {

public int x =33;

}

public class TestOne implements one,Two{

public void test() {

System.out.println(one.x);

System.out.println(Two.x);

}

public static void main(String[] args) {

new TestOne().test();

}

}

二、   当父类常量与实现接口常量同名的时候,子类也是无法解析的。

package com.immoc.test;

interface one {

static int x = 11;

}

interface Two{

final int x = 22;

}

class Three {

public int x =33;

}

public class TestOne extends Three implements one,Two{

public void test() {

System.out.println(one.x);

System.out.println(Two.x);

System.out.println(x);

}

public static void main(String[] args) {

new TestOne().test();

}

}

三、当在子类中自己定义一个x,才能打印自己定义的那一个

package com.immoc.test;

interface one {

static int x = 11;

}

interface Two{

final int x = 22;

}

class Three {

public int x =33;

}

public class TestOne extends Three implements one,Two{

int x = 44;

public void test() {

System.out.println(one.x);

System.out.println(Two.x);

System.out.println(x);

}

public static void main(String[] args) {

new TestOne().test();

}

}

四、接口也是存在继承关系的,并且可以继承多个父接口。

Ifather接口

package com.immoc.test;

public interface Ifather {

void say();

}

Ison接口

package com.immoc.test;

public interface Ison extends Ifather {

void run();

}

Demo类实现Ison接口需要重写两个方法。

package com.immoc.test;

public class Demo implements Ison{

@Override

public void say() {

// TODO Auto-generated method stub

}

@Override

public void run() {

// TODO Auto-generated method stub

}

}

Ifather2接口

package com.immoc.test;

public interface Ifather2 {

void fly();

}

Ison可以同时继承Ifater和Ifather2接口

package com.immoc.test;

public interface Ison extends Ifather,Ifather2 {

void run();

}

则在Demo类中需要重写三个方法。

package com.immoc.test;

public class Demo implements Ison{

@Override

public void say() {

// TODO Auto-generated method stub

}

@Override

public void run() {

// TODO Auto-generated method stub

}

@Override

public void fly() {

// TODO Auto-generated method stub

}

}

如果两个接口中有默认的重名方法,则子类需要自己重写一个自己的重名方法。这就是java当中接口的重名关系。

{{o.name}}

{{m.name}}

程序员灯塔

转载请注明原文链接:Java面向对象之接口学习(三)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值