Java children execute method of ancestor - java

There are three classes - Children, Father, and Ancestor. Children extends Father, and Father extends Ancestor, like below:
public class Ancestor {
public void test() {
}
}
public class Father extends Ancestor {
#Override
public void test() {
}
}
public class Children extends Father {
#Override
public void test() {
}
}
How I can use Ancestor's test() method in Children's test() method? I want to skip Father's test() method.

You can't. Java does not permit doing something like super.super.method(). The reasons for this are outlined in this excellent answer, but the bottom line is that it violates encapsulation.
If the functionality is really necessary, and it makes sense to do something like this, you can always add a method in your Father class that just calls the super.test() method, but doing things like this is usually bad practice. Unless you have some really good reasoning, rethink your code. There shouldn't really be any necessity to call a method from either this nor super.

The short answer is, you can't. It violates encapsulation and is generally bad practice. A better way to accomplish what you want would be to make Ancestor.test() abstract and have a new protected method like Ancestor.baseTest(); Then, you could call Ancestor.baseTest() from Father, Child and any other subclass that wants to access the logic.

Related

Do I need to implement inherited methods in Java?

I'm a beginner when it comes to Java and I have two questions that really concern me...
Isn't #Override kind of a code duplication? I mean, let me consider a situation.
I implement a function in the Parent class. Then I create a Child class that inherits this method from the Parent class. Now I am able to use this function without implementing it once again in the Child class - it works. But is it a good practice? Or maybe I should write #Override and implement this function once again?
Do I need to #Override setters and getters from the Parent class? (And implement them in Child - just like in the previous question). Or maybe they should be abstract in Parent class?
Thanks in advance :)
class Animal { /*Parent class*/
private int numOfLegs;
protected String sound;
public Animal(int numOfLegs, String sound) {
this.numOfLegs = numOfLegs;
this.sound = sound;
}
public int getNumOfLegs() {
return numOfLegs;
}
public void makeSound() {
System.out.println(sound);
}
}
class Dog extends Animal{ /*Child class*/
public Dog(int numOfLegs, String sound) {
super(numOfLegs, sound);
}
#Override /*Is it necessery to implement an inherited function?*/
public void makeSound() {
System.out.println(sound);
}
/*Do I need to implement an inherited getter?/*
}
The point of overriding, as the name suggests, is to override/replace/change the behaviour of the parent method. There is no point in overriding a method with the same implementation. You can just use the inherited method if you don't want to change anything.
You must override your method from parent class only of you want to override super class. But you must override every methodsfrom Iterface when you implement it by some of your class.
So, you can you use from some method in Dog class like super.makeSound() or Just makeSound() if you don't want to override it in Child class, for example do not make sound but make jump or something else.
Isn't #Override kind of a code duplication?
If you duplicate the same code (as in the parent) you lose the point for what override is intended: Define a new code for a method you parent has already defined.
For the contrary, it's about code re-use: we re-use what it is useful for use (the methods that we don't override and don't want to repeat in a whole separate new class) and we only override which needs to be changed.
...is it a good practice?
It is not a matter of a good practice to override a code but a matter of modify the behavior of a method inherited from a parent class (there are lots of reasons for why we do this)
Or maybe I should write #Override and implement this function once
again?
Again, you only override the method if you need to.
Now, what it is a good practice is when you override a method you SHOULD annotate it with #Override (if you don't do it, it works too, but you will lose the useful info the compiler can give with this annotation: for example check that you're actually overriding the method and not creating an overload because of the method signature is different from the one in the parent)
Do I need to #Override setters and getters from the Parent class?
Sometimes, only if the use case requires it, but it is not common to see this.
Or maybe they should be abstract in Parent class?
About they being abstract, well, that is a completely different (but closely related, I know) topic.
They should be abstract only if in the parent class there is not enough information to implement those methods, information that depends on the concrete implementation (in the children classes).
Example use case:
Most of the birds fly, right, some other don't: If we create a class Bird we can have a method getMovement which returns "Fly". Now if we create a class Penguin we need to override that, because they don't fly. Also in the Bird class there is a method getCover which returns "Feathers", in the class Penguin we don't need to override it, because they have feathers too :)
public class Bird {
// for most birds this is OK, they fly
public String getMovement() {
return "Fly";
}
public String getCover() {
return "Feathers";
}
}
public class Penguin extends Bird {
// penguins don't fly, so we need to override the parent method in order to create more realistic penguins
#Override
public String getMovement() {
return "Walk";
}
//we don't override getCover because penguins do have "Feather"
}

How to hide method of parent interface in Java?

I have 3 classes.
public interface Operation {
void move();
void delete();
void search(String criteria);
}
public abstract class AbstractOperationProcessor implements Operation {
public void move() {
// some logic
}
}
public class DailyMailProcessor extends AbstractOperationProcessor{
// need to hide this method because I don't want to provide them to customer
public void delete() {}
public void search(String criteria) {}
}
What I need is to hide methods delete() and search(String) from API. How can I do it without changing interface Operation and abstract class AbstractOperationProcessor?
You cannot. The best you can do is implement stubs that throw something like NotImplementedException and document this fact.
I would use this as an opportunity to examine the definition of the top-level interface. If you need to hide some of its methods then the real problem may be that it aggregates unrelated functionality. You may need to split it into two separate interfaces.
Remember, you can "inherit" (i.e. implement) multiple interfaces.
As the other answers already stated: You cannot hide a method of a superclass. There is also a good reason that you cannot do this: Polymorphism allows you to pass any object of a subtype where an object of a supertype is needed. In your case, if you have a method
void foo(Operation op){op.delete()}
you can call
foo(new DailyMailProcessor())
As you can see, foo does not know the exact type of op, but because delete is in Operation's interface, the method delete can be called.
If you happen to want to remove some methods from a subtype's interface, you are probably not implementing a behavioral subtype! I suggest you have a look at the Liskov Principle, which is one of the fundamental principles in object oriented programming.
If, what you have is not a behavioral subtype, you are wrongly trying to achieve code reuse by inheritance. You should use composition instead. Favor composition over inheritance (Item 16, Effective Java). The reason to favor composition in your case is obvious: You do not have to throw an UnsupportedOperationException (as mentioned in the other answers) and hereby gain static safety.
Edit: To clarify what I mean when telling you to use composition: Instead of having class DailyMailProcessor extending Operation, give it an member variable of type Operation and forward calls to the methods you want to support to the member variable.
public interface Operation {
void move();
void delete();
void search(String criteria);
}
public class DailyMailProcessor {
private Operation op;
public DailyMailProcessor {/*instantiate op*/}
void move() {op.move();}
}
You cannot do that. Every method declared in the interface should be implemented by the class. What you can do is you just implement those methods but do not give any definition to it.
Edit:
As suggested in the comments, UnsupportedOperationException might be a better choice.
Original answer:
There is the IllegalStateException just for that. Just make all the methods you don't want to implement throw that. Just do:
public class DailyMailProcessor extends AbstractOperationProcessor {
public void delete() {
throw new IllegalStateException();
}
public void search(String criteria) {
// do something useful here
}
}
the best solution that handle your probleme, if, and only if you want to have it in an elegante way, is to use a component system and it would look some this like that:
abstract class Component {
abstract void perform();
}
abstract class Move extends Component {
void perform() { ... }
}
class AbstractOperationProcessor {
List<Component> components;
...
}

How to use abstract methods linked with enforced call for other methods

I am facing the following problem:
I defined an abstract class that contains the public generate, clone, etc. methods that must be implemented by the subclass. However I would like to ensure that when these public methods are called certain other methods are also executed within the abstract class.
An obvious solution would be to make a protected abstract method to be implemented and a public non-abstract method that calls the abstract one and all the other methods that I need.
For example:
abstract class Representation {
public void generate(int variable) {
myFunction();
generateAbstract(variable);
}
protected abstract void generateAbstract(int variable);
private void myFunction() {
//do something
}
}
My question is how to solve it a nicer way, or if this is the way to go how to name the function in a user-friendly way.
Thanks!
Your way of solving this issue is so standard that it even has a name: it is called Template Method Pattern. The idea is to provide a public method that executes the steps of your algorithm at high-level, and use overrides of protected abstract methods in subclasses to deal with lower-level steps of the algorithm. This is the correct way of addressing the problem.
I would do it as you are doing it. I would make the wrapper method either
final so I can't be blown away in a subclass, or
document the hell out of the methods, indicating that the abstract method MUST be called...
#dasblinkenlight's answer identifies the design pattern that addresses your problem: Template Method. I like this Template Method link more than the wikipedia entry that answer references. Also, I like answers with code examples:
// Demonstrate the template method design pattern
// straight out of GoF example
abstract class AbstractClass {
// Final ensures extender does not override, but depends on your design
final void templateMethod() {
primitiveOperation1();
primitiveOperation2();
}
// document extenders should keep as protected
// so clients do not call directly
protected abstract void primitiveOperation1();
protected abstract void primitiveOperation2();
}
public class ConcreteClass extends AbstractClass {
#Override
protected void primitiveOperation1() {
System.out.println("ConcreteClass.primitiveOperation1()");
}
#Override
protected void primitiveOperation2() {
System.out.println("ConcreteClass.primitiveOperation2()");
}
}
I think your suggested method is quite elegant enough. I've certainly solved the same problem in this way before. I'd possibly call your method doGenerate() (or something without the word Abstract in it).
I think the easiest way to do this would be to ensure that super.generate is called. Since Java doesn't have a good mechanism for informing a class of when it has been subclassed (others like Ruby do), there's not much you can do to force a subclass that implements an abstract method to call another method.
As pointed out before, what you suggested is the correct approach according to the Template method pattern. What is left is the naming issue. I would not call the function to be overwritten "generateAbstract" because when it is implemented it is not abstract anymore. I recommend something like "makeGenerate()" which reflects the original function and implies what it does.
abstract class Representation {
public void generate(int variable) {
myFunction();
makeGenerate(variable);
}
protected abstract void generateAbstract(int variable);
private void myFunction() {
//do something
}
}
public class ConcreteClass extends Representation {
#Override
protected void makeGenerate() {
...
}

Way to make Java parent class method return object of child class

Is there any elegant way to make Java method located within parent class return object of child class, when this method is called from child class object?
I want to implement this without using additional interfaces and extra methods, and to use this without class casts, auxiliary arguments and so on.
Update:
Sorry that I was not so clear.
I want to implement method chaining, but I have problems with methods of parent class: I lose access to child class methods, when i call parent class methods... I suppose that I'v presented the core of my idea.
So the methods should return this object of this.getClass() class.
If you're just looking for method chaining against a defined subclass, then the following should work:
public class Parent<T> {
public T example() {
System.out.println(this.getClass().getCanonicalName());
return (T)this;
}
}
which could be abstract if you like, then some child objects that specify the generic return type (this means that you can't access childBMethod from ChildA):
public class ChildA extends Parent<ChildA> {
public ChildA childAMethod() {
System.out.println(this.getClass().getCanonicalName());
return this;
}
}
public class ChildB extends Parent<ChildB> {
public ChildB childBMethod() {
return this;
}
}
and then you use it like this
public class Main {
public static void main(String[] args) {
ChildA childA = new ChildA();
ChildB childB = new ChildB();
childA.example().childAMethod().example();
childB.example().childBMethod().example();
}
}
the output will be
org.example.inheritance.ChildA
org.example.inheritance.ChildA
org.example.inheritance.ChildA
org.example.inheritance.ChildB
org.example.inheritance.ChildB
What are you trying to achieve ? It sounds like a bad idea. A parent class should not know anything about its children. It seems awfully close to breaking the Liskov Substitution Principle. My feeling is that your use case would be better serve by changing the general design, but hard to say without more informations.
Sorry to sound a bit pedantic, but I get a bit scared when I read such question.
Simply to demonstrate:
public Animal myMethod(){
if(this isinstanceof Animal){
return new Animal();
}
else{
return this.getClass().newInstance();
}
}
You can call this.getClass() to get the runtime class.
However, this is not necessarily the class that called the method (it could be even further down the hierarchy).
And you would need to use reflection to create new instances, which is tricky, because you do not know what kind of constructors the child class has.
return this.getClass().newInstance(); // sometimes works
I know exactly what you mean, in Perl there is the $class variable which means if you call some factory method on a subclass, even if it is not overridden in the subclass, if it instanciates any instances of $class an instance of the subclass will be created.
Smalltalk, Objective-C, many other languages have a similar facility.
Alas, there is no such equivalent facility in Java.
If you are using Kotlin, you can create an extension function
abstract class SuperClass
class SubClass: SuperClass()
fun <T : SuperClass> T.doSomething(): T {
// do something
return this
}
val subClass = SubClass().doSomething()
public class Parent {
public Parent myMethod(){
return this;
}
}
public class Child extends Parent {}
And invoke it like
Parent c = (new Child()).myMethod();
System.out.println(c.getClass());
Is this solution is correct? If it is, then, how is it different from the #1 solution?

How to override method to invoke superclass' superclass method? [duplicate]

This question already has answers here:
Closed 13 years ago.
Part of me thinks that this shouldn't be possible (even if it is), but I'll ask anyway.
Given the following class hierarchy (Grandparent and Parent are from a 3rd party and thus, not under my control), how would I override myMethod() in Child such that it bypasses the overridden implementation in Parent and invokes the one in Grandparent?
class Grandparent {
public void myMethod() {
// do stuff
}
}
class Parent extends Grandparent {
#Override public void myMethod() {
super.myMethod();
// do something else
}
}
class Child extends Parent {
#Override public void myMethod() {
// ??? I want to *only* do what Grandparent did here
}
}
Pretend that the Parent class provides a lot of other helpful behavior and is a crucial element of Child's hierarchy (in other words, I'm not looking for "make Child a subclass of Grandparent".
The idea behind inheritance is that each class defines their methods how they need, so you don't need to be inspecting any code.
It seems like you're subclassing here just to re-use code, and that's not the idea of subclassing.
Maybe you should have a helper member to do some of the tasks you need, instead of subclassing, and have both "Child" and "Parent" classes extend "Grandparent".
The main question you need to ask yourself is: "Is Child really a descendant of Parent, Grandparent or neiter?" In other words, for every instance of Child, can I say it's a Parent?
If the answer is no, then you're subclassing wrongly: inheritance is supposed to mean something, not just code re-use (i.e. Ford IS ALSO a Car, not just "Ford" uses "Car" methods).
Assuming that I couldn't touch the code in Parent or Grandparent and assuming that I'm not, as Seb suggested (and as Steve apparently agreed) simply misusing inheritance entirely:
I'd create a local instance of a Grandfather object (or a local class extending Grandfather, if it's abstract) and access its interpretation of myMethod() directly. Of course, depending on how much state information myMethod() is supposed to read and/or manipulate, the amount of work involved could be anything from "easy" to "excruciating".
It's an ugly solution, and, depending on how much state information is accessed, could be brittle as hell. But if Grandfather is reliably stable and/or myMethod() is fairly self-contained, it could work. The devil is in the details, as always.
I definitely agree with Seb that this is re-use, not inheritance. But, hey. Re-use is often a Good Thing.
Not possible.
I would create a final helper method in grandparent instead. And have this method (which is overridden) call that helper.
class Grandparent {
public final void myHelperMethod() {
// do stuff
}
public void myMethod() {
myHelperMethod();
}
}
class Parent extends Grandparent {
#Override public void myMethod() {
super.myMethod();
// do something else
}
}
class Child extends Parent {
#Override public void myMethod() {
// ??? I want to *only* do what Grandparent did here
myHelperMethod();
}
}
Do you have control of the Parent class?
If so, could you add a method (myNewMethod) to the Parent that calls myMethod on Grandparent, and call myNewMethod from Child?
(I'm not a Java person, so don't know if you can only call a method in a superclass from an override of that method in a subclass)
class Grandparent {
public void myMethod() {
myHelperMethod();
}
}
class Parent extends Grandparent {
#Override public void myMethod() {
super.myMethod();
// do something else
}
public final void myNewMethod() {
super.myMethod();
}
}
class Child extends Parent {
#Override public void myMethod() {
// ??? I want to *only* do what Grandparent did here
myNewMethod();
}
}

Categories