Suppose I have a class A:
public class A { public A(){....} public void method1() {...} };
And an instance of that class:
A anA = new A();
Is there any way to override the method1()
only for anA
? This question arises when I write a small painting program in which I have to extend the JPanel
class several times just to make minor changes to the different panels that have slightly different characteristics.
The answer is No, you cannot override the same method in one class. The anonymous inner class is a different class. Many classes can exists in same class body (inner classes for that matter) and overriding rules applies to classes and not src files.
"The ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is "close enough" and then to modify behavior as needed. The overriding method has the same name, number and type of parameters, and return type as the method that it overrides.
If a method cannot be inherited, then it cannot be overridden. A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final. A subclass in a different package can only override the non-final methods declared public or protected.
@Override @Override annotation informs the compiler that the element is meant to override an element declared in a superclass. Overriding methods will be discussed in Interfaces and Inheritance. While it is not required to use this annotation when overriding a method, it helps to prevent errors.
You can do the following:
A anA = new A() { public void method1() { ... } };
This is the same as:
private static class myA extends A { public void method1() { ... } } A anA = new myA();
Only with the exception that in this case myA
can be reused. That's not possible with anonymous classes.
You can create a an new anonymous class on the fly, as long as you are using the no-arg constructor of your class A
:
A anA = new A() { @Override public void method1() { ... } };
Note that what you want to do is very close to what is known as a lambda, which should come along the next release 8 of Java SE.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With