In JavaScript I can write:
myobject.doSomething = function() {
// stuff..
}
So how do I use this @Override-thing of Java to achieve the same?
In JavaScript I can write:
myobject.doSomething = function() {
// stuff..
}
So how do I use this @Override-thing of Java to achieve the same?
You cannot override a method of a single object
in Java
because Java
is not a functional language. You can, however, override the method in a subclass of the class
declaring your method.
Declaring an anonymous class:
new MyClass() {
@Override void myMethod() {
....
}
}
Do you mean something like this?
Main.java
private class SuperClass
{
public void myMethod()
{
System.out.println("Test!");
}
}
private class ChildClass extends SuperClass
{
@Override
public void myMethod()
{
System.out.println("Testtest!");
}
}
public class Main
{
public static void main(String[] args)
{
SuperClass superInstance = new SuperClass();
ChildClass childInstance = new ChildClass();
superInstance.myMethod();
childInstance.myMethod();
}
}
You can do this when the object is being created using an anonymous class; basically you create a subclass for the one object only. Example:
Label label = new Label() {
@Override
public void setText(String text) {
super.setText(text);
System.out.println("Text has been set to " + text);
}
};
label.setText("Test");