This question already has answers here:
When do you use Java's #Override annotation and why?
(27 answers)
Closed 4 years ago.
(Newbie to Java, old time C# guy.)
I have noticed a lot of the use of #Override in Android example code. I thought that all Java methods were by default "Virtual"?
What then does #Override do?
Example:
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
It's an annotation that you can use to tell the compiler and your IDE that you intend the method that has that annotation to be an override of a super class method. They have warning/errors in case you make mistakes, for example if you intend to override a method but misspell it, if the annotation is there the IDE or the compiler will tell you that it is not in fact overriding the super class method and thus you can determine why and correct the misspelling.
This is all the more important for Android applications and activities for example, where all of the calls will be based on the activity lifecycle - and if you do not properly override the lifecycle methods they will never get called by the framework. Everything will compile fine, but your app will not work the way you intend it to. If you add the annotation, you'll get an error.
This code for the beginner who really want to understand about the #Override process, this will help you! (Remind inheritance concept of Java.)
For example, the Fish class might have two subclasses: FreshwaterFish and SaltwaterFish.
These subclasses would have all the features of the Fish class, but could further customize the objects through new attributes and behaviors or modified behaviors from the parent class Fish. For example, the FreshwaterFish class might include information about the type of freshwater environment lived in (e.g. river, lake, pond, or puddle).
Similarly, the SaltwaterFish class might customize the makeBabyFish() method such that the fish eats its mate after breeding (as defined in the super class) by using the override mechanism, like this:
public class SaltwaterFish extends Fish
{
#Override
public void makeBabyFish(Fish fishSpouse, int numBabies) {
// call parent method
super.makeBabyFish(fishSpouse, numBabies);
// eat mate
eat(fishSpouse);
}
}
The Override-Annotation is just a hint for the compiler that you want to overwrite a certain function. The compiler will then check parent-classes and interfaces if the function exists there. If not, you will get a compile-error.
Its basically just a safety mechanism.
For reference, see this article (override is explained somewhere in the middle)
Override is mostly used in case of defining a method.Overriding is similar to way its meaning.
I will try to explain in very lame way.Suppose if you have Oncreate() Method already defined and have the associated properties with it. and Again when you call Oncreate() method in your code for certain object,the code which you have written now... will override the formally defined property or inherited property of Oncreate() for your application.
Related
This question already has answers here:
Java: how to implement private abstract methods?
(2 answers)
Closed 3 years ago.
A theoretical question about "Object oriented programming" in general, and in java specifically.
So say I have a "SpaceShip" class which is abstract, and would like to extend it and create another class which is "SpaceShipTypeX" and "SpaceShipTypeZ"
maybe more in the future, but anyhow both should have some same code/methods like say, "fire()", "speedUp()" etc...
I can implement these in the abstract class so I can reuse the code (Great!)
and/or change it for each SpaceShip.
now The problem occurs when I want to implement a method which is "getHit()" - which reduced the SpaceShip's health when it gets a hit.
But I want it to be implemented in each of the classes in a different manner also I want it to be private in them, but they all have the same method signature so it must be In the abstract class for polymorphism reasons, though I want it to be private because I want to hide it from the api, because its and internal function and doesn't want other users to be bothered with it.
So because I cannot use private functions in the abstract class I'm stuck.
what should I do? (Also I want to avoid using protected because It will be shown in the java docs and is sort of a "public api" because some user can work in the same package and accidentally use it")
some code for fun:
public abstract class SpaceShip {
public health = 100;
public abstract void fire();
public abstract void speedUp();
private abstract void getHit(); // <------ It's not allowed (and doesn't make sense but I need it)
}
spaceshipY:
public class SpaceShipX extends SpaceShip{
public void fire(){
// TODO: implement
}
public void speedUp() {
// TODO: implement
}
}
THE METHOD I WOULD LIKE TO HIDE FROM THE public API:
private void getHit() {
// TODO: reduce some health (IMPLEMENT)
}
Your case is exactly about protected modifier usage.
Of course, you can use private modifiers in abstract classes.
But only if you 200% sure that logic that implemented inside will not be changed in descendants - otherwise it will be a real pain to support.
The second issue that if you implicitly call these private methods implicitly in descendants via superclass - it becomes hard to remember and understand what's really going on (especially if you will have a 3-4-more level of inheritance)
You can't accomplish exactly what you are trying to do. Private methods are not inherited by subclasses. This is because calls to private methods are statically bound at compile time, so dynamic binding (i.e. polymorphism) cannot take place.
As others have indicated, the closest things available to what you are looking for is either protected, or package private.
Please note that package private methods are only inherited by a subclass if the subclass is within the same package.
Definig something in the superclass as a means of reusability. I am not sure to what extent that would be a good practice.
Are you sure the algorithm of getting Hit would be aways the same ?
What if one ship can get explosive damage, the other ship get electric damage , and the third ship get hit by EMP. Would the damage aways be the same ?
With respect to the question, Yes you can use private method in abstract class, but I would recommend you to read Composition over inheritance before making your choice:
https://en.wikipedia.org/wiki/Composition_over_inheritance
UPDATE:
You should can think in this direction:
Ship has 1 or more Vulnerabilities
Vulnerability has type - Fire, Explosive,EMP ..... You can think of it as a function over the Damage.
Ship can produce Damage.
Damage can have one or more types.
This is a producer consumer way of thinking that involves mroe composition than actual inheritance.
There are three or four types of method identifiers. Private, Public, Protected, and/ or Final. Protected Methods allow inheritance access by its subclass but not by any unrelated class.
I have two classes. Let's call them PostClass and CommentClass. Both classes implement the Reportable interface:
public interface Reportable {
void report();
boolean isReported();
. . .
Now I need to add two additional methods to each one of the classes. These methods logically fit into the same interface but needs to have different names. For example:
PostClass will have methods -> remove(), restore()
CommentClass will have methods -> hide(), show()
Question: What would be the preferred way to design this change? The options are as I see it:
Create an additional interface which will extend the Reportable interface. Problem: Too many interfaces
Add all four new methods into the Reportable interface and then just leave the irrelevant two methods unimplemented in each class. Problem: Untidy/ugly
Don't worry about having a few more interfaces, as long as their use and purpose is clear. These 2 options are valid:
PostClass implements RemovableReportable, which extends Reportable; And
CommentClass implements HideableReportable, which extends Reportable.
PostClass implements both Reportable and Removable; And
CommentClass implements both Reportable and Hideable.
But adding all four new methods into the Reportable interface and leaving two methods unimplemented in each class is very wrong, since it does not lead to code which is clean and easy to understand and use. The developer would have to learn which method to use in each case, thus making your code more difficult to use and modify. And what happens if some developer calls the wrong method? If the wrong method does nothing, bugs may go unnoticed. If it throws an exception, this will only catch bugs at runtime. And if it calls the other method then you have two ways of doing the same thing, which is also bad and confusing.
Unused methods in an interface are a code smell, and may indicate a design flaw.
If they do the same thing, then make up names that encompass the function; although that doesn't sound like what you want given the existing names.
Option 3: Create two new interfaces, Removable and Hideable and have each class implement the appropriate interface(s).
On second thought, I would probably recommend using hide() and show() since that seems to capture what's happening best.
While the question would likely be classified as opinion based, my approach would be to still add two methods (show(),hide()) to the interface and have the classes implement it.
Below are few other options :
If you are using JDK8 you can try adding the above two methods as default-methods in the interface so that it does not immediately break the existing implementation.
Also, apparently its possible to invoke the abstract method from a default method in the interface so it would technically be possible to have two generically named abstract methods and two (or four more) that are specifically named default methods but that would be overkill and would only add to the confusion.
You could consider having a total of six new methods. show and hide being abstract and also showPost/hidePost and showComment and hideComment being default classes which in turn invoke the abstract show and hide respectively. That way even if some implementation class calls the wrong alias by mistake it would still invoke the correct implementation (in theory).
Whatever I am going to describe in this answer is purely my opinion and subjective.
The following points must be kept in mind when designing this:
Any method added to Reportable (or in general any supertype) should be applicable to all subtypes regardless.
A method should describe a behaviour of the class, something that the class is capable of 'doing'.
Point 2 explanation
Think of the method postClass.remove(), which can be read as 'A PostClass knows how to remove...'. But remove what? Itself? From where?
For me, 'removing' and 'restoring/adding' seems like something that can be done on a Collection of PostClass or CommentClass by and not something that these classes do themselves. If I guess correctly, this is indeed how you must be using PostClass and CommentClass in your application (i.e. as a Collection of some sort). Now, a PostClass or CommentClass can get a callback onRemove(), onRestore(), onHide() or onShow() to do what's necessary for each of this actions when being removed/restored/hidden/shown.
The advantage of callbacks is that a class can choose to call super if they don't intend to do something special during the action.
Design 1 - Reportable has the behaviour of being hidden,shown,restored and removed
So, for all 'reports' of your application, you can add these callbacks to the Reportable interface itself.
public interface Reportable {
void report();
boolean isReported();
void onRestore();
void onRemove();
void onHide();
void onShow();
}
Usage could be something like this
public class User {
private List<Reportable> reports;
//... more User related code
public void deleteReport(Reportable report) {
//give report a chance to cleanup
report.onDelete();
//delete from user's list of reports
this.reports.remove(report);
//more code
}
Design 2 - Having separate interfaces
public interface Viewable {
void onHide();
void onShow();
}
public interface Disposable {
void onRemove();
void onRestore();
}
public class PostClass implements Reportable, Disposable {
}
public class CommentClass implements Reportable, Viewable {
}
Usage for this is pretty self explanatory I guess.
I prefer Design 2 as it seems more clean and adheres to 'SOLID' design principles.
Hope this helps.
In java or Android there are #Override annotations. What does it mean? I found that it is used when method is from subclass or inherited interface's method, I want to know further and other is #SuppressWarnings its also Anonation, if yes how many annonation used by java and for which purpose.
This question is also answered here, and quite succinctly:
Android #Override usage
It's an annotation that you can use to tell the compiler and your IDE that you intend the method that has that annotation to be an override of a super class method. They have warning/errors in case you make mistakes, for example if you intend to override a method but misspell it, if the annotation is there the IDE or the compiler will tell you that it is not in fact overriding the super class method and thus you can determine why and correct the misspelling.
This is all the more important for Android applications and activities for example, where all of the calls will be based on the activity lifecycle - and if you do not properly override the lifecycle methods they will never get called by the framework. Everything will compile fine, but your app will not work the way you intend it to. If you add the annotation, you'll get an error.
In other words, if you add #Override this helps you make sure you are really overriding an existing method! Pretty darn useful.
Overriding means that you are changing the behavior of a method inherited from a parent class, without changing the signature. The #Override annotation is used to mark this. It is strongly linked with the concept of polymorphism. Example:
public class A {
public void foo() {
System.out.println("A");
}
}
public class B extends A {
#Override
public void foo() { // I want to change the way foo behaves
System.out.println("B"); // I want to print B instead of A
}
}
public static void main(String[] args) {
A a = new A();
a.foo(); // prints A
A b = new B(); // I can use type B because it extends A
b.foo(); // I have overriden foo so it prints B now
}
Just to ensure that you are actually overriding it at compile time, and to improve readability
Example:
class Animal{
public void eat(Food food){
}
}
class Person extends Animal {
#Override
public void eat(String food){
}
}
This will give you compile time error since you are not actually overriding it (see the type of food)
#override its an annotation i.e meta data introduce in jdk 1.6 . If you don't write it before override method , it won't make any difference but it just use to increase the readability of compiler.
To mark that you really implement or change a method. Like meantined it's checked at compile time. That is you for instance you get an error if you want to implement #Override public void equals(final Car pObject); instead of #Override public void equals(final Object pObject);.
Just go the source for the definition of both annotations, besides other additional details: the #Override and the #SuppressWarnings from the Java specs.
It sounds like your question is more about annotations in general, so I'll answer that. Annotations provide extra meta data about the item that is being annotated. This allows other code to use that information to decide how to run. More detailed description. There are a large number build into the language, but you can write your own.
The two examples you gave tell the compiler extra information about the code it is compiling. When it sees #Override, it checks to ensure that the method is actually overriding a method. When it sees #SuppressWarnings, it know that it should ignore any compiler warnings, of the given type, that exist inside the block of code.
They can be used outside of compilers as well. There are a number of libraries that have you annotate a class object and it uses that meta data to build a database or parse an xml file.
This question already has answers here:
When do you use Java's #Override annotation and why?
(27 answers)
Closed 9 years ago.
This is a newbie question.
I read that JVM's execution starts from searching for the methodname from lowest class in the hierarchy and if the method is not available in that class it traverses to the parent class looking for the method.
If this is the case then why do we need to use "#override" for adding custom logic to the inherited class ?
The below example illustrates my question
class superclassA
{
method()
{
}
}
class subclassB extends superclassA
{
#Override
//While executing if JVM starts looking for the method name from the lowest hierarchy
//then why do we have to use "override" as the methodname will be matched from the lowest level itself?
method()
{
--custom subclass specific code...
}
}
If this is the case then why do we need to use "#override" for adding custom logic to the inherited class?
We don't. The #Override annotation has no technical meaning - it exists to document the fact that this method overrides one in the superclass, which has some advantages:
If you look at the code, it tells you there is an superclass method that might be important to understand what this method does
You will get a compiler error if the superclass method's signature changes in a way that the subclass method does in fact not override it anymore.
You can get a compiler warning if you override a method without using the annotation, in case you do it inadvertantly.
#Override simply helps Java compiler detect errors in source code, compilers are generate an error if a method annotated with #Override does not override it in fact.
It is not mandatory to annotate a method that overrides a supertype methods with #Override.
You don't need #Override. But it's a useful annotation that causes the compiler to check whether or not you are really overriding the method that you say you are. When you #Override a method that is not actually overriding a method, the compiler will inform you of this discrepancy. Additionally, it just makes your code more clear: since all methods in Java are implicitly virtual, and a method in a derived class with the same signature as that of a non-final method in a super class implicitly overrides it1, adding #Override makes the code easier for humans to understand.
1: To be clear, you can not have a method in a derived class with the same signature as a final method in a super class.
In .NET, one can specify a "mustoverride" attribute to a method in a particular superclass to ensure that subclasses override that particular method.
I was wondering whether anybody has a custom java annotation that could achieve the same effect. Essentially what i want is to push for subclasses to override a method in a superclass that itself has some logic that must be run-through. I dont want to use abstract methods or interfaces, because i want some common functionality to be run in the super method, but more-or-less produce a compiler warning/error denoting that derivative classes should override a given method.
I don't quite see why you would not want to use abstract modifier -- this is intended for forcing implementation by sub-class, and only need to be used for some methods, not all. Or maybe you are thinking of C++ style "pure abstract" classes?
But one other thing that many Java developers are not aware of is that it is also possible to override non-abstract methods and declare them abstract; like:
public abstract String toString(); // force re-definition
so that even though java.lang.Object already defines an implementation, you can force sub-classes to define it again.
Ignoring abstract methods, there is no such facility in Java. Perhaps its possible to create a compile-time annotation to force that behaviour (and I'm not convinced it is) but that's it.
The real kicker is "override a method in a superclass that itself has some logic that must be run through". If you override a method, the superclass's method won't be called unless you explicitly call it.
In these sort of situations I've tended to do something like:
abstract public class Worker implements Runnable {
#Override
public final void run() {
beforeWork();
doWork();
afterWork();
}
protected void beforeWork() { }
protected void afterWork() { }
abstract protected void doWork();
}
to force a particular logic structure over an interface's method. You could use this, for example, to count invocations without having to worry about whether the user calls super.run(), etc.
... and if declaring a base class abstract is not an option you can always throw an UnsupportedOperationException
class BaseClass {
void mustOverride() {
throw new UnsupportedOperationException("Must implement");
}
}
But this is not a compile-time check of course...
I'm not sure which attribute you're thinking about in .NET.
In VB you can apply the MustOverride modifier to a method, but that's just the equivalent to making the method abstract in Java. You don't need an attribute/annotation, as the concept is built into the languages. It's more than just applying metadata - there's also the crucial difference that an abstract method doesn't include any implementation itself.
If you do think there's such an attribute, please could you say which one you mean?
Android has a new annotation out as announced in the Google I/O 2015:
#callSuper
More details here:
http://tools.android.com/tech-docs/support-annotations
If you need some default behaviour, but for some reason it should not be used by specializations, like a implementation of a logic in a non abstract Adapter class just for easy of prototyping but which should not be used in production for instance, you could encapsulate that logic and log a warning that it is being used, without actually having to run it.
The base class constructor could check if the variable holding the logic points to the default one. (writing in very abstract terms as I think it should work on any language)
It would be something like this (uncompiled, untested and incomplete) Java (up to 7) example:
public interface SomeLogic {
void execute();
}
public class BaseClass {
//...private stuff and the logging framework of your preference...
private static final SomeLogic MUST_OVERRIDE = new SomeLogic() {
public void execute() {
//do some default naive stuff
}
};
protected SomeLogic getLogic() { return MUST_OVERRIDE; }
//the method that probably would be marked as MustOverride if the option existed in the language, maybe with another name as this exists in VB but with the same objective as the abstract keyword in Java
public void executeLogic() {
getLogic().execute();
}
public BaseClass() {
if (getLogic() == MUST_OVERRIDE) {
log.warn("Using default logic for the important SomeLogic.execute method, but it is not intended for production. Please override the getLogic to return a proper implementation ASAP");
}
}
}
public GoodSpecialization extends BaseClass {
public SomeLogic getLogic() {
//returns a proper implementation to do whatever was specified for the execute method
}
//do some other specialized stuff...
}
public BadSpecialization extends BaseClass {
//do lots of specialized stuff but doesn't override getLogic...
}
Some things could be different depending on the requirements, and clearly simpler, especially for languages with lambda expressions, but the basic idea would be the same.
Without the thing built in, there is always some way to emulate it, in this example you would get a runtime warning in a log file with a home-made-pattern-like-solution, that only your needs should point if it is enough or a more hardcore bytecode manipulation, ide plugin development or whatever wizardry is needed.
I've been thinking about this.
While I don't know of any way to require it with a compile error, you might try writing a custom PMD rule to raise a red-flag if your forgot to override.
There are already loads of PMD rules that do things like reminding you to implement HhashCode if you choose to override equals. Perhaps something could be done like that.
I've never done this before, so I'm not the one to write a tutorial, but a good place to start would be this link http://techtraits.com/programming/2011/11/05/custom-pmd-rules-using-xpath/ In this example, he basically creates a little warning if you decide to use a wildcard in an import package. Use it as a starting point to explore how PMD can analyze your source code, visit each member of a hierarchy, and identify where you forgot to implement a specific method.
Annotations are also a possibility, but you'd have to figure out your own way to implement the navigation through the class path. I believe PMD already handles this. Additionally, PMD has some really good integration with IDEs.
https://pmd.github.io/