Martafix Martafix - 1 year ago 38
Java Question

Java - using interface as "extends"

I'd like to have object, that acts as if it extends 2 classes, so i can pass it as parameter.

public abstract class Entity //object that can be rendered
{
private int xPosition;
private int yPosition;
private int xSize;
private int ySize;
// +getters and setters
}

public interface Activatable // makes object activatable
{

public void activate();

}


public class Engine extends Entity implements Activatable
{
private Entity Slave;

//constructor, getters, setters

public void move(){
// move Slave
}

public void activate(){
move();
}

public void render(Grafics g){
//render
}
}


But in java, object can extend only 1 other object, so tried to use interface, but it didn't work. The Entity works normally:

//in another class
private Engine engine = new Engine(...);

public void checkCollision(Entity e)
{
//do the logic
}

this.checkCollision(engine);


but the interface does not:

private Engine engine = new Engine(...);

public void activateRandom(Object o implemets Activatable)
{
//do the logic
}

this.activateRandomly(engine);


I hope its understandable, pls help :)

Answer Source

This is invalid syntax:

public void activateRandom(Object o implemets Activatable)

If you're trying to make the method parameter be of type Activatable, then you'd do that like any other type:

public void activateRandom(Activatable o)

An interface is a type just like any other. It can't be directly instantiated like a class, but it can be used as a type declaration just like a class can. For example:

Activatable myObj = new Engine();

Note that a "class" and a "type" are two (sometimes subtly) different things. An interface isn't a class, but both a class and an interface are types.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download