父类及接口中同名变量和方法
一、父类与接口或接口之间出现同名变量(在接口中属于常量,只能用接口名.常量名
调用)
-
接口跟类同级,在实现接口和继承父类都存在相同变量时,导致子类无法抉择
-
解决方法
- 在子类的方法中显示表明要输出的变量是父类还是接口的变量。(
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()方法
*/
三、接口之间存在同名方法
- 参数列表+返回值 都相同:实现类只要实现一次此方法即可
- 参数列表相同+返回值不同:实现类无法直接实现两个方法(IDE报错),因为不满足方法重载原则
- 参数列表不相同:实现类可以分别实现两个方法,可以方法重载
//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();
}
}