Java method that can't be callable but can be overridden - java

If I don't want that a method on my class can be called, I just make it private.
But if I want to allow that method to be overridden, I have to make it protected
Is it possible to have a method on an abstract class that can't be called but can be overridden? (I guess not, but is there any workaround?)
Use case:
abstract class Super {
protected void finalize() {
}
public final void doThings() {
// do stuff
finalize();
}
}
and whoever wanted to extend the class:
class Sub extends Super {
#Override
protected void finalize() {
closeSockets();
alertSomeone();
}
}
But I don't want other classes calling mySub.finalize();

Instead of overwriting a method, the sub-class may provide the super-class with a Runnable which contains the code to be executed. You could do something like this:
public class Super {
private final Runnable subClassCode;
public Super(Runnable finalizeCode) {
subClassCode = finalizeCode;
}
public final void doThings() {
// do stuff
subClassCode.run();
}
}
public class Sub extends Super {
public Sub() {
super(() -> {
// code to be executed in doThings()
});
}
}
You dont need to set the Runnable instance in the constructor. You may also give access to a protected setFinalizeCode(Runnable) method but that method could also be called by other classes within the same package as Super.

Related

Template Method calling super and use implementation

I have implemented Template Method, and i faced with this situation:
public class ProductTemplate() {
protected Item getItemFromShop(){
processItemPrice();
callOrderSummary();
}
protected void processItemPrice() {
Do some logic....
}
protected void callOrderSummary()
Do some logic....
}
}
public class ImportedProduct extends ProductTemplate() {
#Override
protected Item getItemFromShop() {
super.getItemFromShop(); // When i call this super method, they will use the processItemPrice() from the implementation
}
#Override
protected void processItemPrice() {
Do another logic....
}
}
My doubt is.. can in call an super method and if inside this super method there is a method call and i have this method overridden, what method implementation the class will use?
Solution: OK It's works fine. but when i have one class that calls one single method overridden, is it useless have this:
public class SimpleProduct extends ProductTemplate(){
public processItemPrice(){
super.processItemPrice()
}
}
This ProductTemplate implements an interface, and is used within Strategy pattern.. is it right?
The easiest way to understand this sort of thing is to code debugging prints into your code and see what happens.
Cleaning up your code (so it compiles) and adding some prints:
public class ProductTemplate {
protected Item getItemFromShop() {
processItemPrice();
callOrderSummary();
return null;
}
protected void processItemPrice() {
// Do some logic....
System.out.println("ProductTemplate.processItemPrice()");
}
protected void callOrderSummary() {
// Do some logic....
System.out.println("ProductTemplate.callOrderSummary()");
}
}
public class ImportedProduct extends ProductTemplate {
#Override
protected Item getItemFromShop() {
return super.getItemFromShop(); // When i call this super method, they will use the processItemPrice() from the implementation
}
#Override
protected void processItemPrice() {
// Do another logic....
System.out.println("ImportedProduct.processItemPrice()");
}
public static void main(String[] args) {
new ImportedProduct().getItemFromShop();
}
}
If you run the ImportedProduct class (which is now possible because I added a main method), you'll get the output:
ImportedProduct.processItemPrice()
ProductTemplate.callOrderSummary()
showing that the overridden method in your subclass is indeed called.
Note: There's no need to override the getItemFromShop method as you do. It does nothing different from the overridden method.

implement an abstract method in derived class as static

I have these 2 classes
class A {
public void foo1() {
...;
foo2();
...;
}
protected abstract foo2();
}
class B extends A {
public foo2() {
......
}
I need foo2 to be static so I can do B.foo2() but I also want the functionality in class A to remain.n
Any suggestions?
}
You can't override static methods or implement abstract methods as static.
Static methods are defined on a class definition, not on a class instance. Abstract methods are defined on a class instance.
What you said doesn't make sense in fact.
Although I don't quite get why you need to do it, there is a workaround:
class B {
#Override
public void foo() {
fooUtil();
}
public static void fooUtil() {
// your impl here
}
}
Then you can do B.fooUtil() instead, and using its behavior to override A.foo().

How to call the abstract method from a class which is not in hierarchy in java

Below is my code. I have the abstract class Myabatract which has the method myMethod and I have a subclass MySubClass in which I have overridden the myMethod. In my client class
I have a method callMethod from which I want to directly call the myMethod of Myabatract class is this possible?
abstract class Myabatract {
public void myMethod() {
System.out.println("This is from Myabatract");
}
}
class MySubClass extends Myabatract {
public void myMethod() {
System.out.println("This is from MySubClass");
super.myMethod();
}
}
class Client{
public void callMethod(){
}
}
You can create an anonymous implementation of the abstract class. This is particularly easy given the fact that it does not use any abstract methods.
class Client {
public void callMethod() {
Myabatract instance = new Myabatract() { /* nothing to implement*/ };
instance.myMethod();
}
}
As a user of the MySubClass type, you have no way to call the Myabatract method because it has been overridden, unless MySubClass were to expose it. Your only recourse would be to create another method that exposed the super method from within MySubClass (or other child implementations).
It's important to note that this will not work:
class Client {
public void callMethod() {
MySubClass instance = new MySubClass() {
#Override
public void myMethod() {
super.myMethod();
}
};
instance.myMethod();
}
}
super is the non-anonymous class, MySubClass, which means nothing is actually changing. Interestingly, this can be worked around in C++ using the scope resolution operator (::).
It's also worth pointing out that you are calling super.myMethod() in your implementation of MySubClass, which does invoke the Myabatract method.

Can't cope with inheritance

I have (some pseudocode):
public class Thrd extends Thread{
protected void letUsFinalize(){
int a = 0; // Just for debugging.
}
}
public class FreeThread extends Thrd{
#Override
protected void letUsFinalize() {
FreeThread.this.interrupt();
}
}
Please, have a look at the picture. Our object now is of class FreeThread (visible in the Variables subsection). So, I come to the upper break point in the picture, press Step into and I occur at the lower break point. I mean that I occur in the method of the class Thrd (superclass).
What should I do so that the method of subclass would execute in this case?
If the object that you are using is an instance of FreeThread, then calling object.letUsFinalise() will call the method from FreeThread.
It looks like you are calling letUsFinalise() from the super class, so it's not possible to call the subclass' method unless you are using a static object to it (demonstrated below).
public class SuperClass {
public void method(){
Objects.object.method();
}
}
class SubClass extends SuperClass{
#Override
public void method(){
System.out.println("I'm the sub class!");
}
}
class Objects{
public static SubClass object = new SubClass();
}
I suggest that you create a static object of FreeThread and use that to call the method, as shown above.

Prevent abstract implementation from overriding certain method

I have an interface called Worker which I want to expose so that the end-user can simply call:
Worker w = WorkerFactory.createInstance();
w.mainBit();
How can I prevent classes which extend my AbstractWorker class from providing their own implementation of the mainBit method?
This is the structure I have so far:
interface Worker {
void mainBit();
}
class WorkerFactory {
public static Worker createInstance() {
return new WorkerImpl();
}
}
abstract class AbstractWorker implements Worker {
#Override
public void mainBit() {
this.doThing1();
this.doThing2();
}
public abstract void doThing1();
public abstract void doThing2();
}
class WorkerImpl extends AbstractWorker {
#Override
public void doThing1() {
}
#Override
public void doThing2() {
}
#Override
public void mainBit() {
// I don't want classes to override this functionality
}
}
You can do that by making the method final.
Use the final keyword.
public final void mainbit ()
...
Mark the method as final, which prevents overriding:
public final void mainBit()
If you want to always use the AbstractWorker's mainBit, make it final in this class. This way, the subclasses won't override it.
Mark it final inside you abstract class (in Java). No other subclass will be allowed to override it.

Categories