Use of super vs. this in cases of no override - java

I'm currently taking an intro level CS course at my university. My professor insists on using this.method() rather than super.method().
Example: I'm calling a method from a superclass, getOneIntersectingObject(), and since it's in the superclass I usually call it by using super.getOneIntersectingObject(). However, my professor wants me to call it using this.getOneIntersectingObject().
I understand that this searches the current class and executes its method() over any similarly named method() in any superclasses, but my question is this:
Why use this if you're not overriding the method? Is this just common programming etiquette?

Why use this if you're not overriding the method?
Because
It's less complicated to use this consistently rather than using this or super depending on what method you're calling.
You may add an override later; using super would require that you go back and fix all of the places you called it.
And yes, because it's the normal thing to do.
This is a CW, anyone else who wants to jump in with reasons, please don't hesitate.

You don't have to use this or super if you don't use an override. If you have an override, this.method() calls the method of the child class (derived class) and super.method() calls the method of parent class. super.method() is like saying, "i want parent class's method() to execute, not the child's".

Related

Implementing a method of interface is overriding or not in java

I know this might be crazy but today one of my friend puzzled by asking when we implement an interface in java is it considered as method overriding. I told him it is not overriding as we are providing working(definition) of method first time when we implement any interface. To support multiple inheritance java provide interface but he was not convinced and was arguing. Please bring some light on to the topic.
The term "overriding" applies when there is an existing implementation of the method . The correct term is "implementing" for interfaces and other abstract declarations.
The #Override tag is used for both cases - it is used when:
The method does override or implement a method declared in a supertype. --javadocs
And from Wikipedia:
Method overriding, in object oriented programming, is a language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes.
Note that interfaces can have default methods - redefining these methods overrides them:
When you extend an interface that contains a default method, you can ... redefine the default method, which overrides it.
Besides linking to "canonical" sources, I'm not sure what advice to offer on winning a semantic argument with your friend. Perhaps you could ask him what the distinction is between "implementing" and "overriding", and what word he would use instead of "overriding" for the concept of redefining an existing method.
At first glance, interfaces just define API. Since there is no super method to override, the implementations is the first method.
But since Java 5, it's customary to add #Override annotations even for methods which come from interfaces. The main reason here is to catch problems which happen when people change an interface: Now you have a method which is "dangling" - there is no API which says that the method has to be there. The annotation causes an error if you remove a method from the interface, catching this so you can properly clean up all the code.
But that still doesn't mean the implementing method overrides anything.
Except that an interface is very much an abstract class with abstract methods in the byte code. And abstract methods do override.
My feeling is that you can argue both ways but the argument is moot unless you have a use case there the answer to the question actually has a real impact on the code. And here, it doesn't really matter since the compiler hides all the ugly details.

Why should we override a method? [duplicate]

This question already has answers here:
Why is method overloading and overriding needed in java? [duplicate]
(2 answers)
Closed 8 years ago.
Recently I was asked this question "why should one override a method? "
I replied, if I have a class with 10 methods and I want to use all of its functionality except one method, then I will override that method to have my own functionality.
Then the interviewer replied in that case why cant we write a new method with a different name and use that method instead.
Yes this is also right. Now I am confused. What is the real objective in overriding a method?
Can anyone please tell me? Thank you all in advance.
If you will give another name to the method in derived class, you cant invoke it with same interface. You can always invoke it through base class pointer.
i.e.
Base p = new Derived();
p.overrideMethod();
If Derived class is derived from Base then it will automatically call the derived version and not of Base. In case of different name, it is not possible. It is called code against interfaces and not implementations.
.
why cant we write a new method with a different name and use that method instead
It is because we want to use polymorphism. You could tell the interviewer this example: There is a module that calls specific methods on objects you give it; now imagine you can't change that module (e.g. no source). You can't tell it to use a different method but you can give it an object of a subclass which has overridden that method. To the module it will appear that nothing changed.
In practice it is also often the case that you could change that module but dont want to.
I replied, if I have a class with 10 methods and I want to use all of
its functionality except one method, then I will override that method
to have my own functionality.
=> Very often a way to break the Liskov Substitution principle ... => very bad OO design
You have many examples on the web of this "break" but a you can find a good explanation here.
The benefit of overriding is: ability to define a behavior that's specific to the subclass type which means a subclass can implement a parent class method based on its requirement.
One uses interfaces to allow for multiple implementations and one uses overriding to simplify the implementation of an interface (e.g. when implementing a WindowListener, one typically extends and overrides a method of WindowAdapter so that one does not need to provide definitions for the cases where the default behavior is sufficient). Adding a new method rather than overriding would not work in this case, because the caller understands the interface and invokes its methods; the whole point of overriding here is to change the behavior for the calls to the interface. If you simply added a new function, then the caller would have to know about it, which defeats the entire isolation between the consumer of a piece of functionality and the provider of that functionality which is what interfaces are intended to provide.
Overriding is a feature that is available while using Inheritance.
It is used when a class that extends from another class wants to use most of the feature of the parent class and wants to implement specific functionality in certain cases.
In such cases we can create methods with the same name and signature as in the parent class. This way the new method masks the parent method and would get invoked by default.
The main objective of overriding is code reuseablity which can be advatageous in big projects,it also provide flexiblity means you can pass different sets of input from any class and get the output

Override constructor in all subclasses IntelliJ

I wanted to know if there is possibility to generate constructors for all subclasses in IntelliJ.
I mean if i have many subclasses and somewhere in development stage I wanted to add new constructor, with a flag, for example. Is there a way to generate this constructor in all subclasses too?
I wanted to know if there is possibility to generate constructors for all
subclasses in IntelliJ?
The answer would be no and one of the reason would because it is design specific.
When you create a subclass and define a non default constructor in it you have the liberty to call any one of the overloaded superclass constructor from it. Which one would be design choice as initialization of superclass variables may depend on it. Never the less call to one of the overloaded super class constructor must be 1st statement of subclass constructor. If you do not provide any, call to default constructor of super class is inserted by default by the JVM. However in that case if your super class does not have default constructor(you have explicitly provided some parameterized constructor) then compiler error will occur.

When to call super in method

I'm having a problem understanding when to call a super in a overridden method. According to this post it should be at the bottom, but my colleagues disagree.
What is your opinion on this topic?
The answer is depends. The actual decision depends on what you are doing in the overridden method and also the behavior expected by the base class when you are overriding a particular method.
The documentation of the method you are overriding should provide the details of expected behavior while overriding. My personal preference call super in the first place.
It depends on what your overridden method is doing. If you're talking about a constructor, you have to call super first to ensure that the superclass is properly constructed before you go about setting its state. If it's another method, where you put the call depends on whether you're transforming the input parameters (super needs to go after that) or the return value (super goes before this).
The "post" you linked to is documentation for an automated code-audit tool, not a recommendation, and it has options for telling it that subclasses ought to be calling super at either the beginning or the end of their methods.
My opinion is that the rules should comply with your coding standards. If you can't agree, its a good sign it is not clear that you need to be checking this for your project.
Personally I have always put super calls at the start unless there as a very good reason.

Checking what subclass the object is in, then running a method in that subclass - Java

I have an abstract class called Policy, and two subclasses DepreciablePolicy and ExpirablePolicy
I have an array of Policy, policies[]
I want to check what subclass my object is in (if it's a Policy, DepreciablePolicy or ExpirablePolicy)
I did this by using this if statement.
if (this.policies[polNum] instanceof DepreciablePolicy){
For each type of subclass, there is a different method I have to run.
Only problem is that I'm only able to use the Policy methods, but not the subclass methods or constructors.
Is there a way I can do this?
This is inheritance done the wrong way. The whole point of polymorphism is that your code doesn't care which subclass an object is. Anything you need to do should be expressed through the Policy, which should really be an interface. Your code should interact with a Policy based on that interface, and the subclasses choose how to react.
That being said, you're probably looking for simple down-casting:
DepreciablePolicy d = (DepreciablePolicy) policy;
This is nothing better than a poor bandage on a bad design, though.
For each type of subclass, there is a different method I have to run.
Then you've misdesigned it. Define an abstract method in Policy, have all the derived classes implement it according to their own requirements. Then just call the method.

Categories

Resources