Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override a function without extending the class

Tags:

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.

like image 330
Max Avatar asked Aug 13 '12 06:08

Max


People also ask

Can we do override in same class?

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.

Can you override a method from extended class?

"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.

Can I override method without inheritance?

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.

What does @override do in Java?

@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.


2 Answers

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.

like image 63
jensgram Avatar answered Sep 18 '22 10:09

jensgram


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.

like image 42
Alexandre Dupriez Avatar answered Sep 22 '22 10:09

Alexandre Dupriez