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"
}
Related
I have a game system with a base class called GameRoom.
In this class I have some boilerplate code for what every GameRoom instance needs.
In individual room classes I extend the GameRoom class, overriding the update and render methods of the base GameRoom class, but that makes my tilemaps etc. not render.
I want the boilerplate code to keep rendering whilst being able to run a custom one (with the exact same name) within the GameRoom subclasses.
How do I do that?
You can call an overridden method by using super instead of this.
class Example extends Parent {
#Override
void method() {
super.method(); // calls the overridden method
}
}
If you want to force every subclass to call a method from the parent class, Java doesn't provide a direct mechanism for that. But you can use a final function that calls abstract functions to allow a similar behavior (the template method).
abstract class Parent {
final void template() { // the template method
System.out.println("My name is " + this.nameHook());
}
protected abstract String nameHook(); // the template "parameter"
}
class Child {
#Override
protected String nameHook() {
return "Child"
}
}
Then you can run the program by calling the template method, which is only defined by the parent class, and it will call the subclasses' hook methods, which they all must have implemented.
If you have something like:
abstract class Room{
abstract void render(Canvas c){
//impl goes here
}
}
Then in your subclasses you can do:
class SpecificRoom extends Room{
void render(Canvas c){
super.render(c);//calls the code in Room.render
}
}
Let's say you have a class that extends Activity and implements MyInterface, where Activity contains public final void setProgress(int progress) and MyInterface contains public abstract void setProgress(int progress)
I need to override the method from the interface, but I can't because Activty says it's final and can't be overridden.
What do I do?
Example:
public class MyActivity extends Activity implements MyInterface
{
#Override
protected void onCreate(Bundle bundle)
{
//stuff goes here
}
//Cannot override the final method from Activity
#Override
public void setProgress(int progress)
{
}
}
Let's also extend this question and say you don't have access to the source of MyInterface to change it, what does one do in such situations?
Use a decorator Design Pattern.
and here's a simplified example of the decorator pattern.
(adapted from the interwebs and polygenelubricants' answer on SO)
Note: before we begin remove the abstract keyword from the interface, that's wrong syntax
The class hierarchy is restructured as static inner classes so that the whole example is contained in one compilation unit (as seen on ideone.com):
Here's a diagrammatic overview of intended class hierarchy
public class AnimalDecorator {
static interface Animal {
public String makeNoise();
public void wagTail();
//other methods
}
static class Dog implements Animal {
public final String makeNoise() { return "woof"; }
public final void wagTail() { //do wag tail action }
}
static class DogDecorator implements Animal {
//delegate
private Animal animal;
public DogDecorator (Animal animal){this.animal = animal;}
public String makeNoise() { animal.makeNoise();}
public void wagTail() { animal.wagTail();}
}
static class LoudDog extends DogDecorator {
#Override public String makeNoise() {
return "WOOF WOOF WOOF!!!";
}
}
}
So here we have a simple Animal hierarchy, with Dog subclass. We also have a DogDecorator decorator -- also an Animal -- that simply delegates all methods to another Animal. That is, it doesn't really do any effective decoration, but it's ready to be subclassed so that actual decorations can be added.
We only have two methods here, makeNoise() and wagTail(). We then create the class we want LoudDog and use it. (Consider the case where Animal has many methods; then Normal would be most valuable).
Note that we can even stack one decoration on top of another. The exact implementation details may vary, but this simplified example pretty much captures the essence of the decorator pattern.
Steps
Subclass the original "Component" class into a "Decorator" class (see UML diagram);
In the Decorator class, add a Component pointer as a field;
Pass a Component to the Decorator constructor to initialize the Component pointer;
In the Decorator class, redirect all "Component" methods to the "Component" pointer; and
In the ConcreteDecorator class, override any Component method(s) whose behavior needs to be modified.
See also
Effective Java 2nd Edition, Item 18: Prefer interfaces to abstract classes
Related questions
Interface vs Abstract Class (general OO)
Is it just me or are interfaces overused?
You cannot override the final method because in the Java programming language, the final keyword is used to define an entity which cannot later be changed.
form Java Language Specification
Never tried but can give it a try.
You must implement the MyInterface in subclass too and can override the setProgress method of MyInterface and not of its superclass.
Should say..a good question:)
Edit:
In this case, the class cannot override the final method. So either your interface will have the exact same signature as the parent class (hence the interface is implemented automatically by inheritance), or you create a method with a different name.
The solution would largely depend on the circumstances, there's no textbook solution here.
Don't have your MyActivity implement MyInterface and instead create anonymous or inner class that implements it.
This ways you still have access to all MyActivity components and functions from setProgress(int) which is completly separate from final Activity.setProgress(int).
Basicaly I have a need for several methods that do the same thing but with different parameters the sub-classes can chose from, and still force the implementation.
Is this a correct approach/design ?
EDIT: I have edited the addItem() body, these methods contain the final logic that is used to handle the passed parameters
public abstract Class A {
public abstract void addItemImpl()
addItem(String s) {
// do stuff
}
addItem(Collection c) {
// do stuff
}
addItem(Item item) {
// do stuff
}
}
public Class B extends A {
addItemImpl() {
addItem("text, text2")
}
}
public Class C extends A {
addItemImpl() {
addItem([item, item2])
}
}
No, this will not work.
You will not be able to define the "doStuff()" method because you have to handle the parameters. You provide not enough information to give you detailed help. But it's possible that generics might come in handy:
public abstract Class A<T> {
public addItem(T t) {
// dostuff with t
}
}
public Class B extends A<String> {
}
public Class C extends A<Collection> {
}
This is a perfect case for: Favor composition over inheritance.
Your subclasses don't fully benefit from the superclass and don't depend on its implementation details. Then define an interface for the contract B and C must obey (addItemImpl()) and compose them with A.
Ask yourself: is B really an A? is C really and A?
What you have is technically correct, but with out knowing what addItem actually does it is difficult to know if this is the best solution. My guess would be that there probably is a better way.
If addItem essentially set values to be used in the doStuff, I would just do that work in the Class B and C instead. Any others that need to do it the same way as B could extend it instead of A.
Edit: Based on your edit, I would say this is probably a bad example to use an abstract class. There is no truely shared functionality. An interface would be more appropriate as you need a different implementation for each. You are just trying to hide that inside an abstract class. I would change A to an interface along with using generics.
Only go the abstract class route if there is actually shared code that is exactly the same in all the classes without having to do any tricks to make it work (like above).
If you need force implementation for few methods, then Abstract methods are ideal.
But be careful only the very first Non-Abstract sub-class of the Super-class is bound to implement all the abstract methods in it....
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() {
...
}
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?