我直接举个例子吧interface I{ void interfaceMethod(); int CONST=10; }class A{ public void interfaceMethod(){ System.out.println("sameA"); } public void anotherMethod(){ System.out.println("aaa"); } public static int CONST=20; }class B extends A implements I{ public void interfaceMethod(){ System.out.println("sameB"); } public void anotherMethod(){ System.out.println("bbb"); } } public class Test{ public static void main(String[] args){ A a=new A(); a.interfaceMethod(); a.anotherMethod(); B b=new B(); b.interfaceMethod(); b.anotherMethod(); A c=new B(); c.interfaceMethod(); c.anotherMethod(); System.out.println(a.CONST); // System.out.println(b.CONST); //加上报错 System.out.println(c.CONST); //这个不会
} }sameA aaa sameB bbb sameB bbb sameB bbb 20 20----------------------- 上面的class A,class B extends class A后面如果换着加implements I结果也是相同的可以告诉我为什么结果是这个吗,特别是第三第四个输出,还有注释的两处
还有这个忘记贴了main中全部是这样的 A a=new A(); a.interfaceMethod(); a.anotherMethod(); B b=new B(); b.interfaceMethod(); b.anotherMethod(); A c=new B(); c.interfaceMethod(); c.anotherMethod(); A d=(A)c; d.interfaceMethod(); d.anotherMethod(); System.out.println(a.CONST); // System.out.println(b.CONST); //这句报错 System.out.println(c.CONST); //这个就不会
接口,抽象类的区别
如果是方法的话,A中有和I同名的方法,如果B继承A实现I的话,它要实现I中的这个方法,虽然编译通过了,但是在B中访问这个方法时,调用的是实现接口I的那个方法,是不是A中的方法就相当于被重写了??另外想问下@Override这个是不是只在eclipse中才可以用,好像JCreator中用会报错
void interfaceMethod();
int CONST=10;
}class A{
public void interfaceMethod(){
System.out.println("sameA");
}
public void anotherMethod(){
System.out.println("aaa");
}
public static int CONST=20;
}class B extends A implements I{
public void interfaceMethod(){ System.out.println("sameB");
}
public void anotherMethod(){ System.out.println("bbb");
}
}
public class Test{
public static void main(String[] args){
A a=new A();
a.interfaceMethod();
a.anotherMethod();
B b=new B();
b.interfaceMethod();
b.anotherMethod();
A c=new B();
c.interfaceMethod();
c.anotherMethod();
System.out.println(a.CONST);
// System.out.println(b.CONST); //加上报错
System.out.println(c.CONST); //这个不会
}
}sameA
aaa
sameB
bbb
sameB
bbb
sameB
bbb
20
20-----------------------
上面的class A,class B extends class A后面如果换着加implements I结果也是相同的可以告诉我为什么结果是这个吗,特别是第三第四个输出,还有注释的两处
a.interfaceMethod();
a.anotherMethod();
B b=new B();
b.interfaceMethod();
b.anotherMethod();
A c=new B();
c.interfaceMethod();
c.anotherMethod();
A d=(A)c;
d.interfaceMethod();
d.anotherMethod();
System.out.println(a.CONST);
// System.out.println(b.CONST); //这句报错
System.out.println(c.CONST); //这个就不会
至于抽象类和接口,个人觉得抽象类就像画画,先画个框架,再临摹框架画再添东西,接口好像链条上的配件,配件的规格给你了,你做个什么挂上去都可以。