A reminder about the errors that occurred during Java training.
Sample.java
abstract class A{
abstract void aMethod();
}
interface B{
void bMethod();
}
//A inheritance
class OnlyA extends A{
public void aMethod(){};
}
//A inheritance / B implementation
class AB extends A implements B{
public void aMethod(){};
public void bMethod(){};
}
public class Main {
public static void main(String[] args){
A[] a = new A[]{new OnlyA(), new AB()};
//Abstract class method call
a[0].aMethod();
a[1].aMethod();
//Interface method call
a[1].bMethod();
}
}
/*
Main.java:26: error: cannot find symbol
a[1].bMethod();
^
symbol: method bMethod()
location: class A
*/
Could not call.
Main.java
public class Main {
public static void main(String[] args){
A var1 = new AB();
B var2 = new AB();
AB var3 = new AB();
var1.bMethod(); //This is no good
var2.bMethod(); //This is okay
var3.bMethod(); //This is also okay
}
}
In this case, it seems that you have to declare it with the interface type or the type that implements it.
I thought I was accessing the method of the instance class AB extends A implements B
directly, but since I declared it with class A
, I wonder if I'm accessing that first?
In the case of inheritance only / implementation only, both parent and child are defined, so it is unlikely that cannot find symbol
will appear, but if inheritance and implementation are performed at the same time like this, you have to be careful.
(I haven't used the interface so much, but now it's a good idea)
I felt that I needed to study more.
Recommended Posts