public class Main {
public static void main(String[] args) {
Object[] array = new Object[1];
Piece piece = new Piece();
array[0] = piece;
array[0].move();
}
}
class Piece{
public void move(){
System.out.println("hello");
}
}
Line 6 doesn't not work and I am not sure why. Shouldn't array[0] give me piece and piece.move() call the method in the class?
You are casting Piece as Object when you add it to the Object array.
Try this:
public class Main {
public static void main(String[] args) {
Piece[] array = new Piece[1];
Piece piece = new Piece();
array[0] = piece;
array[0].move();
}
}
class Piece{
public void move(){
System.out.println("hello");
}
}
It's because on line array[0] = piece;
you are assigning Piece
object to Object
which is valid because Object
is the parent class of all.
But when you do array[0].move();
you are trying to call the move()
method from reference of Object
class. This is not possible because move()
method is not declared in Object
class.
Thus you need to cast like below:
((Piece)array[0]).move();
When you store a Piece
as Object
the compiler does not know anymore that it is a Piece
. You have to explicitly tell it (cast it ((Piece)array[0]).move();
).
Alternatively store objects in Piece[] array
.
I assume the real motivation is storing different pieces types. In this case they all have to have the same base type. This can be achieved by having all pieces types extend the same base class, or implement a common interface:
public class Main {
public static void main(String[] args) {
Movable[] array = new Movable[2];
APiece aPiece = new APiece();
BPiece bPiece = new BPiece();
array[0] = aPiece;
array[0].move();
array[1] = bPiece;
array[1].move();
}
}
interface Movable {
void move();
}
class APiece implements Movable{
@Override
public void move(){
System.out.println("APiece moved ");
}
}
class BPiece implements Movable{
@Override
public void move(){
System.out.println("BPiece moved ");
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.