When to call super in method - java

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.

Related

Use of super vs. this in cases of no override

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".

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.

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.

Extending fluent interface

I'm starting using Fluent Assertions and I like it a lot, but wonder if it's possible to extend the existing tests in a general way like this:
add method hasSizeAtLeast(int limit) in GroupAssert
add method startsWithIgnoringCase(String prefix) in StringAssert
use alternatives like x.either().isIn(someSet).or().isNull()
These are just examples what I could need soon. I can do some workaround for each of them, but then I lose the readability and the easy of use of the fluent interface.
My last example is meant to throw iff both x.isIn(someSet) and x.isNull() do.
Here is a post by the author about opening up his API for extending assertions on already handled types. Lesson #1 in particular discusses the change to un-finalize classes. The post also gives an example of sub-classing StringAssert as MyStringAssert.
However, it looks like you cannot extend classes such as StringAssert in a way that maintains the "fluency" of the API. The StringAssert class isn't final, but still it doesn't allow you to parameterize its type (i.e. the "this" type that's returned by methods in StringAssert itself) in subclasses. For example, let's say you add a method checkFoo in MyStringAssert. As you discovered, the following is invalid because the original StringAssert methods return StringAssert:
new MyStringAssert("abcd").contains("a").checkFoo(); // compile-time error!
You only can call your subclass's methods first, which is valid but kind of lame:
new MyStringAssert("abcd").checkFoo().contains("a"); // compiles
You might consider contacting the author, or even submitting a patch to his git project. A possible solution would be to add the parameterized type back into StringAssert, and also provide the StringAssert concrete type via an anonymous subclass within Assertions.assertThat(String), which is the recommended entry point anyway. Then, everybody else can subclass StringAssert as you described. I haven't tested this suggestion either, but it seems to make sense...

why would you need to know whether a method of an abstract class is abstract

I've been asked a question. It is the following:
The API documentation of an abstract class tells you whether a method
is abstract. When and why would you need to know this?
Any help would be appreciated.
You need to know what methods are abstract because you will need to provide implementations for those methods when inheriting the class.
As an extension to Fredrik's answer, it also specifies which behaviour is intended to be changed.
You can usually override a method (if the method is not final and the class is not final) but in practice that can be very tricky if the class is not specifically designed for changes. It may be that existing methods assume some kind of behaviour of the method you override, which is not specified (it happens) and that you do not provide.
By explicitly declaring a method to be abstract you express the intention that the method will be implemented by someone else. It also usually means that the documentation of an abstract method is a bit more complete with regards to expected behaviour.
If you call the abstract method you need to take into account that the actual implementation is elsewhere and may have some variation in behavior.
you have know if the method is abstract, because in that case you have to implement it in your concrete (inherited) class.
I advice you to take a look on the following books about Design Patterns, because they mention these stuff and have practices too:
http://oreilly.com/catalog/9780596007126

Categories

Resources