Can a Parent call Child Class methods? - java

Referring here
A is a precompiled Java class (I also have the source file)
B is a Java class that I am authoring
B extends A.
How can logic be implemented such that A can call the methods that B has.
The following are the conditions:
I don't want to touch A(only as a
last option though that is if no
other solution exists).
I don't want to use reflection.
As stated, if needed I could modify A.
What could be the possible solution either way?

Class A should define the methods it's going to call (probably as abstract ones, and A should be an abstract class, per Paul Haahr's excellent guide); B can (in fact to be concrete MUST, if the method are abstract) override those methods. Now, calls to those methods from other methods in A, when happening in an instance of class B, go to B's overrides.
The overall design pattern is known as Template Method; the methods to be overridden are often called "hook methods", and the method performing the calls, the "organizing method".

Yes it seems that if you override the super/base-classes's functions, calls to those functions in the base class will go to the child/derived class. Seems like a bad design in my opinion, but there you go.
class Base
{
public void foo()
{
doStuff();
}
public void doStuff()
{
print("base");
}
}
class Derived extends Base
{
#Override
public void doStuff()
{
print("derived");
}
}
new Derived().foo(); // Prints "derived".
Obviously all of Derived's methods have to be already defined in Base, but to do it otherwise (without introspection) would be logically impossible.

I would be rather hesitant to do this. Please correct me if I am wrong and then I will delete, but it sounds like you want to maintain an A object along with a B object. If they indeed are not the same object, the "tying together" (that's a scientific term) you'll have to do would be pretty ugly.

Related

Why do we need abstract methods?

I have been studying abstract methods lately and I can't understand why do we need them?
I mean, after all, we are just overriding them. Do you know its just a declaration? Why do we need them?
Also, I tried understanding this from the internet and everywhere there's an explanation like imagine there's an abstract class human then there're its subclasses disabled and not disabled then the abstract function in human class walking() will contain different body or code. Now what I am saying is why don't we just create a function in the disabled and not disabled subclasses instead of overriding. Thus again back to the question in the first paragraph. Please explain it.
One of the most obvious uses of abstract methods is letting the abstract class call them from an implementation of other methods.
Here is an example:
class AbstractToy {
protected abstract String getName();
protected abstract String getSize();
public String getDescription() {
return "This is a really "+getSize()+" "+getName();
}
}
class ToyBear extends AbstractToy {
protected override String getName() { return "bear"; }
protected override String getSize() { return "big"; }
}
class ToyPenguin extends AbstractToy {
protected override String getName() { return "penguin"; }
protected override String getSize() { return "tiny"; }
}
Note how AbstractToy's implementation of getDescription is able to call getName and getSize, even though the definitions are in the subclasses. This is an instance of a well-known design pattern called Template Method.
The abstract method definition in a base type is a contract that guarantees that every concrete implementation of that type will have an implementation of that method.
Without it, the compiler wouldn't allow you to call that method on a reference of the base-type, because it couldn't guarantee that such a method will always be there.
So if you have
MyBaseClass x = getAnInstance();
x.doTheThing();
and MyBaseClass doesn't have a doTheThing method, then the compiler will tell you that it can't let you do that. By adding an abstract doTheThing method you guarantee that every concrete implementation that getAnInstance() can return has an implementation, which is good enough for the compiler, so it'll let you call that method.
Basically a more fundamental truth, that needs to be groked first is this:
You will have instances where the type of the variable is more general than the type of the value it holds. In simple cases you can just make the variable be the specific type:
MyDerivedClassA a = new MyDerivcedClassA();
In that case you could obviously call any method of MyDerivedClassA and wouldn't need any abstract methods in the base class.
But sometimes you want to do a thing with any MyBaseClass instance and you don't know what specific type it is:
public void doTheThingsForAll(Collection<? extends MyBaseClass> baseClassReferences) {
for (MyBaseClass myBaseReference : baseClassReferences) {
myBaseReference.doTheThing();
}
}
If your MyBaseClass didn't have the doTheThing abstract method, then the compiler wouldn't let you do that.
To continue with your example, at some point you might have a List of humans, and you don't really care whether they are disabled or not, all you care about is that you want to call the walking() method on them. In order to do that, the Human class needs to define a walking() method. However, you might not know how to implement that without knowing whether the human is or isn't disabled. So you leave the implementation to the inheriting classes.
There are some examples of how you'd use this in the other answers, so let me give some explanation of why you might do this.
First, one common rule of Object Oriented Design is that you should, in general, try to program to interfaces rather than specific implementations. This tends to improve the program's flexibility and maintainability if you need to change some behavior later. For example, in one program I wrote, we were writing data to CSV files. We later decided to switch to writing to Excel files instead. Programming to interfaces (rather than a specific implementation) made it a lot easier for us to make this change because we could just "drop in" a new class to write to Excel files in place of the class to write to CSV files.
You probably haven't studied this yet, but this is actually important for certain design patterns. A few notable examples of where this is potentially helpful are the Factory Pattern, the Strategy Pattern, and the State Pattern.
For context, a Design Pattern is a standard way of describing and documenting a solution to a known problem. If, for example, someone says "you should use the strategy pattern to solve this problem," this makes the general idea of how you should approach the problem clear.
Because sometimes we need a method that should behave differently in its instances.
For example, imagine a class Animal which contains a method Shout.
We are going to have different instances of this Animal class but we need to implement the method differently in some cases like below:
class Animal:
/**
different properties and methods
which are shared between all animals here
*/
...
method shout():
pass
class Dog extends Animal:
method shout():
makeDogVoice()
class Cat extends Animal:
method shout():
makeCatVoice()
dog = new Animal
cat = new Animal
dog.shout()
cat.shout()
So dog shouts like dogs, and cat shouts like cats! Without implementing the shared behaviors twice
There is a different behavior of shouting in these instances. So we need abstract classes.
Suppose you don't know about implementation and still want to declare a method then we can do that with the help of abstract modifier and making it an abstract method. For abstract method only declaration is available but not the implementation. Hence they should end with ;
Example:
public abstract void m1(); // this is correct
public abstract void m1(){ ... } // this is wrong
Advantage: By declaring abstract method in parent class we can provide guideline to child classes such that which methods are compulsory to implement.
Example:
abstract class Vehicle{
abstract int getNoOfWheels();
}
Class Bus extends Car{
public int getNoOfWheels(){
return 4;
}
}
If you want the short answer, think of this:
You have an abstract class Car.
You implement 2 classes that extend it, Ferrari and Mercedes.
Now:
What if you did one of the following, for the method drive(), common to all cars:
1) changed the visibility of the method,
2) changed the name of the method from driving to Driving,
3) changed the return type, from a boolean to an int
Think about it. It might not seem to make any difference right, because they are different implementations?
Wrong!
If I am iterating through an array of cars, I would have to call a different method for each type of car, thereby making this implementation of abstract useless.
Abstract classes are there to group classes with a common template, that share common properties. One way this helps would be the looping over the array:
Abstract methods ensure that all cars declare the same method,
and therefore, any object of a subclass of Car will have the method drive(), as defined in the abstract class, making the for loop mentioned easy to implement.
Hope this helps.

Why does a superclass implement interface methods which are supposed to be implemented by the child?

Here is a parent class
public class Parent {
public void f() {
}
}
Here is a simple interface
public interface If {
public void f();
}
Here is a child class
public class Child extends Parent implements If{}
My question is:
Although it is Child which claims to implement the interface If, the interface method is implemented in Parent. Why is this allowed?
Why is this allowed?
Because Child satisfies the contract. The contract Child makes, by implementing If, is that it will provide a public f function that accepts no arguments and has no return value. It does that. How it does it, in this case by inheriting it from a superclass, is irrelevant. The contract is satisfied, which is all that matters.
the interface method is implemented in Parent
Not really, it just happens to have the f method. If you did If inst = new Parent() you'd get get a compilation error, because Parent doesn't say it implements If (there's no implements If on it); implementing If isn't part of its contract. Child, on the other hand, does provide that contract, and so If inst = new Child() works just fine.
FWIW, you probably wouldn't do this on purpose, although there's arguably nothing wrong with it. But it could come up if it just happened that the superclass you want to use has a perfect fit for one of the methods in the interface you want to implement.
When that happens, you have three choices:
Do nothing and let Parent's method directly implement the interface method.
Override Parent's method even though you're not going to do anything differently, e.g.:
#Override
public void f() {
super.f();
}
...which really doesn't accomplish anything unless you have code you want to run prior to or after calling Parent's f.
Override f and implement it yourself, ignoring Parent's version. But that only makes sense if Parent's f does something completely different from the interface method's f — in which case, you shouldn't be subclassing Parent in the first place, because if you reimplement f in terms of the interface's behavior, your f won't satisfy the Parent#f contract anymore (in terms of its behavior) and you'll break the "is a" rule for subclassing.
So really, option 1 is perfectly reasonable if it happens organically. You just probably wouldn't set it up on purpose.
It is completely legal because when you implement the method, it works for both.
From class perspective and from interface perspective. A single implementation would serve the both purpose and there is no point of ambiguity it.
There is no way to restrict a Class or Interface to having same method signature, unless you have a relationship with them, but in this case there will be no problems.
The main point of an interface is to list a set of methods, which could be called on any object of a class implementing the interface.
By declaring that a class implements an interface you declare that this set of methods can be called on your class.
As soon as this is the case (e.g. in your example), there is no problem.

java - connecting interface to class member

Say I have an interface A and a class B that implements it.
Now, I also have some class C which extends class D (which means that it can't also extends B) but I also need there the functionality of interface A.
The solution I know is to have a member of A instantiated by B in C (which will implement A) and when implementing the functions of A call the matching function from the member of A.
Is there any way to create some connection between the functions of A and the member inside C? (so that java will know that every time it needs to call a function from A it will directly go and and run the matching function from the A member without me needing to write the code for it for every function of A)
A big thank you is waiting to each one of the helpers...
No. As already stated delegation must be implemented manually.
Having said that, you have a few options to simplify this: If you're working with Eclipse, select Source|Generate Delegate Methods... and select your member variable. Eclipse will then generate all the delegate methods for you. I don't know about other IDEs, but I would be surprised, if NetBeans et al. would not have a similar feature.
Another option, if you actually want to decorate existing collection classes, consider Google Guava's Google Guava's Collection Helpers.
Last, but not least, you could consider restructing your code and decorate your classes using Advices. Advices stem from Aspect Oriented Programming (AOP) and typically use a proxying mechanism to enrich original target classes. This is a rather advanced technique, but if you are determined to go down this road, have a look at Spring's AOP support.
So to sum up, here is your class hierarchies:
package common;
public interface A
{
void doStuff();
}
package commom.impl;
public class B implements A
{
void doStuff() {}
}
package real.service;
public class D
{
void doSomeRealStuff() {}
}
package real.service;
public class C extends D
{
void doSomeRealStuffForGood() {}
}
Assuming that each class is declared in its own source file.
Just to recall from the OP, I assume you need B stuff in C and not really A stuff. Because A is nothing but a contract and you need then the real implemting class to be fetched inside your C class in order to call the declared methods on.
In such a case, you may need to use the Inversion of Responsability approach, so that you declare an instacne of type B inside your C clas then you layer each method from B with a one having the same signature and that do nothing but delegate the real call to the instance member:
package real.service;
import common.A;
import common.impl.B;
public class C extends D
{
private A delegate;
public C ()
{
delegate = new B();
}
void doStuff() {
delegate.doStuff(); // Call the real delegate method when doStuff is called on an isntance of C.
}
void doSomeRealStuffForGood() {}
}
Note that this is a legal OO concept, since you are following an HAS-a even though some could consider it a high coupling.
Otherwise if you are not tied to the B class, and you may drop the declare methods in there for some others, you can declare an inner class that implements the A interface the way you need.
Edit:
Java does not support multiple inheritance, though you have provided a common contract in your A interface, so if you need all those methods (behavior) to be availble in your C class, it would be better to implement it directely and override all the interface methods.

Java: calling the base method class from a second derived class

This is what I'm trying to do:
class A {
void myMethod() {
// execute A
}
}
class B extends A {
void myMethod() {
// execute B
}
}
class C extends B {
void myMethod() {
// execute C
// execute myMethod in A, without touching myMethod in B OR both
}
}
I'd like to do this conditionally, that is sometimes call what's in myMethod inside B and other times not, but always call myMethod inside A.
By calling super.myMethod() in C I get myMethod of B, but I only want myMethod of A. Is that possible? I've heard of "virtual" things, but I don't know how to use them... yet.
No, it is not possible in Java on purpose. Class B overrides and therefore hides the implementation of myMethod in A from further deriving classes. Allowing C to call myMethod of A would violate this encapsulation. Consider a case where B.myMethod performs some updates before internally calling A.myMethod which are important for the correct functionality of B. Without these updates, the contract of B could be violated. Therefore, it should not be possible to call A.myMethod in a derived class without calling B.myMethod.
Usually, your design is flawed if you want to do stuff like this.
Of course, you can do stuff like suggested by Dave in the comments: You can alter the implementation of B.myMethod to call A.myMethod. This is okay, because B retains the control over when to call A.myMethod. Therefore, it can take care that its contract is not violated.
Another idea is to factor out the behaviour you want from A into another method and call this one.
If you need this, A.myMethod() probably does too much. Try to refactor it into several smaller methods with access level protected.
That allows you to call these methods from both B and C.
While I agree with most answers about possibly changing the design, to directly answer you could pass in a variable boolean into the first method. The entirety of the logic in B's method should depend on a conditional if statement depending on the boolean. Make sure to make a call to super.myMethod() outside of this if statement.
Something like this:
void myMethod(boolean execB) {
// execute B
super.myMethod(execB);
if(execB)
{
//B logic
}
}
This is however, not the best in practice, because only B's method is using the variable, hence why refactoring the design might be a good decision.

Best way to invoke method inhereted from Base class : use this , super or call implicitly

I think it's not very useful question, but i think someone can say smth critical.
public class Base{
public void boo(){}
}
public class Derivative extends Base{
1:public void useBoo(){
boo();
}
2:public void useBoo(){
this.boo();
}
3:public void useBoo(){
super.boo();
}
}
[EDIT]
The reason why I asked this question : to avoid recompilation or name confusion in future. And make code more readability and flexable to future changes.
The best one to use is the one you feel is clearest.
BTW: The first example will behave different to the third example, if you add a boo method to Derived.
If you want to be sure that the method invoked is the super class method, definitely use super:
super.boo();
If you want to use a method defined in the current class and if this is not present use the super method use:
this.boo();
//or
boo();
Personally in the second case, if the class is part of a hierarchy, I prefer to explicitly use this.boo() because it's more clear reading the code, to understand where the method is supposed to be. But it's my opinion.
I would only use 1 and 2 (in my case I prefer 2, I like to be explicit about my intentions)
public void useBoo(){
this.boo();
}
I wouldn't use 3 because it means something else semantically, remember that Derivative can also be extended, and boo() may be overridden further down the class hierarchy, and unless you specifically want to call Base.boo() you shouldn't use the super keyword.
Use one of the first two, unless you explicitly want to limit the call to the superclass implementation.
When you override a superclass method, and want to include the behavior of the superclass method, use the third.
Elsewhere, if you use the third, and later you or someone else overrides the superclass implementation of boo() -- in this class or a subclass -- then useBoo() will not use the override. This is usually undesirable except in the override of boo() itself.
Examples:
/** Extends boo method. */
public void boo(){
super.boo(); // Good: you explicitly want to call the superclass method, not call this method again.
}
public void doSomethingThatInvolvesBoo() {
boo(); // Good -- will call this object's implementation,
// even if this is a subclass, even if there are code changes later.
this.boo(); // Good (and equivalent to simply calling boo()).
super.boo(): // Usually bad.
}
Is there anything stopping you from just calling boo()? Or have you overridden it in your own code?
1 and 2 do the same thing, 3 calls the method of Base.
edit: as Simeon said, using super would make it very clear you are calling the method from the Base class.
Having readability in mind super is probably the best because it says here I'm invoking a method from the super class.
While with this you could wonder 'where the hell is this method .. oh ok its in the super class'

Categories

Resources