Java returned type

I have a question about return types in legacy methods in Java. I have a class and an inherited class. There is a specific method in the inherited class. It also inherits a parent class method that returns an instance of itself.

I want something like this class hierarchy:

public class Foo { public Foo bar() { return this; } } public class FooInherited extends Foo { public Whatever baz() { return new Whatever(); } } 

My question is, can I call the inherited method from its instance, and then call the specific method without overriding the method, in order to return the inherited class or explicitly call the classes.

Now I want to have a piece of code like this:

 FooInherited foo = new FooInherited(); Whatever w = foo.bar().baz(); 

I have difficulty with this, but I'm not very sure that Java has a time-saving mechanism for programmers in such situations.

+4
source share
3 answers

If you do not override the method in the subclass, you will need to run the command:

 FooInherited foo = new FooInherited(); Whatever w = ((FooInherited)foo.bar()).baz(); 

However, due to covariant return types in java, you can override it like this:

 public class FooInherited extends Foo { @Override public FooInherited bar() { return this; } ... } 

After overriding, you no longer need to throw, because the static type is foo FooInherited :

 FooInherited foo = new FooInherited(); Whatever w = foo.bar().baz(); 
+4
source

You can use generics, but it quickly becomes ugly.

 class Base<This extends Base<This>> { public This myself() { return (This) this; } } class Sub<This extends Sub<This>> extends Base<This> { public void subOnly() {} } { Sub<?> sub = new Sub<>(); sub.myself().subOnly(); Base<?> base = sub; // base.myself().subOnly(); // compile error } 

An alternative is to explicitly override the method:

 class Base { public Base myself() { return this; } } class Sub extends Base { @Override public Sub myself() { return this; // or return (Sub) super.myself(); } public void subOnly() {} } { Sub sub = new Sub(); sub.myself().subOnly(); Base base = sub; // base.myself().subOnly(); // compile error } 
+4
source

foo.bar() returns an instance of Foo and it does not have a method called baz() , so it is impossible to compile this statement: Whatever w = foo.bar().baz();

+1
source

Source: https://habr.com/ru/post/1442281/


All Articles