一、以下代码当中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面向对象之接口学习(三)