1

In JavaScript I can write:

myobject.doSomething = function() {
    // stuff..
}

So how do I use this @Override-thing of Java to achieve the same?

andy
  • 132
  • 1
  • 10
  • 2
    Can you be please more specific about your issue. And please don't ask us convert code from one language to another. We don't do it. – Rohit Jain Jul 20 '13 at 20:48
  • 1
    You can't do that in Java. It's not a dynamic language like JavaScript. – JB Nizet Jul 20 '13 at 20:51
  • 1
    Java's OO is not prototype-based, unlike that of Javascript. So you cannot do this. – Oliver Charlesworth Jul 20 '13 at 20:51
  • so how does this @Override-thing work? – andy Jul 20 '13 at 20:53
  • `@Override` doesn't *do* anything. It's simply an *annotation*, that [allows the compiler to perform further sanity checking](http://stackoverflow.com/questions/94361/when-do-you-use-javas-override-annotation-and-why). – Oliver Charlesworth Jul 20 '13 at 20:55
  • @partofweb: you're basically asking us to explain you the principle of inheritance and polymorphism in Java. Read a good book or tutorial. This is a too broad question for SO. My advice: try to forget what you know about JS when learning Java. They're completely diferent languages, with completely different approaches. – JB Nizet Jul 20 '13 at 21:01
  • oh. okay. so now that I know that it is not possible in the way I need it, should I delete the question? – andy Jul 20 '13 at 21:03
  • Don't delete it, it could serve for future readers. – Luiggi Mendoza Jul 20 '13 at 21:11

3 Answers3

4

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() {
        ....
    }
}
Michael Lang
  • 3,902
  • 1
  • 23
  • 37
2

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();
    }
}
Patrick
  • 1,717
  • 7
  • 21
  • 28
Zach Latta
  • 3,251
  • 5
  • 26
  • 40
0

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");
Marconius
  • 683
  • 1
  • 5
  • 13