Is it safe to comment out the "#Override"? - java

To get my code to compile - which contained the following:
public class ContactsActivity extends ListActivity implements AdapterView.OnItemClickListener {
Cursor mContacts;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Return all contacts, ordered by name
String[] projection = new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME };
mContacts = managedQuery(ContactsContract.Contacts.CONTENT_URI,
projection, null, null, ContactsContract.Contacts.DISPLAY_NAME);
// Display all contacts in a ListView
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1, mContacts,
new String[] { ContactsContract.Contacts.DISPLAY_NAME },
new int[] { android.R.id.text1 });
setListAdapter(mAdapter);
// Listen for item selections
getListView().setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
. . .
...I had to comment out the "#Override" above the onItemClick() event handler. Is this safe? Should I just shrug my shoulders and say, "OK, that works, I'll forget about it" or is there evil afoot/a hidden problem lurking?

as per my suggestion, it is not good to remove that line. you need to change to JDK version in your eclipse then you will not get such errors. Follow, following steps for it,
Right Click on your Project & select Properties.
Then from the left section Select Java Compiler & select the Version of the JDK you installed. If it is already selected then de-select it & try it.

If you had to comment out the #Override, then your compiler's JDK compliance level isn't set to 1.6, which it should be for Android development. If you're using Eclipse, right click on the project name and select "Properties". Then select "Java Compiler" and adjust as necessary. (You probably inherited a lower JDK compliance level from the workspace. If appropriate, change the compliance level for the workspace instead. This will save having to fix the same problem with new projects.)
But to answer your question: it's safe to comment out #Override. It's just not so great to be using a lower compliance level.

You java version is set to less than 1.6. Starting there, interfaces and not just methods can be market as Override. Right click the project -> Properties -> Java Compiler -> Compiler compliance level to 1.6

From the Java docs:
#Override - the #Override annotation informs the compiler that the
element is meant to override an element declared in a superclass
(overriding methods will be discussed in the the lesson titled
"Interfaces and Inheritance").
// mark method as a superclass method
// that has been overridden
#Override
int overriddenMethod() { }
While it's not required to use this annotation when overriding a method, it helps to prevent errors. If a method marked with #Override
fails to correctly override a method in one of its superclasses, the
compiler generates an error.

It depends. If your compiler is set to target java 5, and the onCreate method is inherited from the interface then yes. Java 5 doesn't support the override annotation on interface methods, whereas Java 6 expects it. This may itself be an indication that your JDK is set up wrong, if you're expecting to target Java 6, what you may be getting is Java 5.

if you'd commented it out, you would not override the methods. So you'd actually do nothing. (My opinion)

Related

Missing annotation: #Override is not shown by compiler in Eclipse IDE

This is kind of weird! but when I implement Collection for my modal class and add unimplemented methods using Eclipse IDE, it is not showing #Override in any of the methods which are generated by clicking on "Add Unimplemented Methods".
public class MadeItACollection implements Collection{
}
When I click on "Add Implemented Methods" the following happens:
public class MadeItACollection implements Collection{
public int size() {
// TODO Auto-generated method stub
return 0;
}
public boolean isEmpty() {
// TODO Auto-generated method stub
return false;
}
.
.
.
.
}
I dont see any #Override. I am compiling my codebase in Java 8. Am I missing something obvious?
As peoples' comments suggest, this is a Code Style option within Eclipse.
You can enable it under Preferences -> Java -> Code Style -- ensure that the "Add #Override annotation for new overriding methods" is checked; after, you can also look into adding it for implementations of interface methods via the link directly underneath. (You can also enable automatic adding of the annotation as a Cleanup or Save action in these menus.)
The #Override annotation isn't strictly required when implementing an interface mainly because you aren't overriding any superclass implementation you are actually implementing the interfaces declared methods. So maybe a #Implements annotation is required, but that's a whole different topic of conversation.
However, it is strongly recommended that you still use the #Override annotation on these methods because:
It explicitly conveys to anybody reading the code that it is an overriding method.
It helps avoid shooting yourself in the foot by throwing a compile time error if you misspell the method you want to override because it will tell you if the method can actually override an existing super method.
Most IDEs actually will help you add this automatically:
Intellij Idea:
Navigate to
File => Settings => Editor => Code Style => Java
And scroll to Override Method Signature and you should find Insert #Override annotation, make sure this is checked.
The Jetbrains documentation says the below about this setting option:
Insert #Override Annotation: Select this checkbox to have IntelliJ IDEA insert #Override annotations automatically.
Eclipse:
Navigate to:
Window => Preferences => Java => Code Style
And look for Add #Override annotation for new overriding methods and make sure it has been checked.
You can also add it as a Save Action by navigating to:
Window => Preferences => Java => Editor => Save Actions
And ensuring that Perform the selected actions on save has been selected and that Additional actions has been selected and ensuring that Add missing Annotations has been configured

Use FindReplaceAction in custom view

In my view I have a StyledText on which I want to open the default eclipse find/replace-dialog (The one that appears in the editor on Ctlr+F).
Therefore I want to instantiate and run the FindReplaceAction but my problem is that this action needs a ResourceBundle as a parameter and I have no idea what this is used for and where I can get it from...
I wonder whether this is actually the way to accomplish this functionality or if there is a way to register my view (that implements IFindReplaceTarget) globally in eclipse to recieve the Ctrl+F shortcut for opening the dialog
You should be able to participate in the standard Find/Replace code by having your view respond to a request for the IFindReplaceTarget in the getAdapter method of your main ViewPart class and setting up the find and replace action.
The adapter is something like:
#SuppressWarnings("unchecked")
#Override
public <T> T getAdapter(Class<T> required) {
if (IFindReplaceTarget.class.equals(required)) {
return (T) ... your find replace target class
}
... other adapters
}
Note: Older versions of Eclipse don't use Generics for this method.
Set up the FindReplaceAction with something like:
ResourceBundle bundle = ResourceBundle.getBundle("my.package.Messages");
FindReplaceAction findReplaceAction = new FindReplaceAction(bundle, "find_replace_action_", this);
findReplaceAction.setActionDefinitionId(IWorkbenchCommandConstants.EDIT_FIND_AND_REPLACE);
IActionBars actionBars = getViewSite().getActionBars();
actionBars.setGlobalActionHandler(ActionFactory.FIND.getId(), findReplaceAction);
The resource bundle needs a Messages.properties file with contents like:
find_replace_action_label=&Find/Replace...
find_replace_action_tooltip=Find/Replace
find_replace_action_image=
find_replace_action_description=Find/Replace

Find Method usages only for specified class in Intelij-Idea

I am using IntelliJ IDEA and I have problem with method usage finding.
Suppose I have interface Worker.
public interface Worker {
void startWork();
void endWork();
}
And I have two implementations.
public class Develper implements Worker {
#Override
public void startWork() {
System.out.println("Developer Start Working");
}
#Override
public void endWork() {
}
}
public class Qa implements Worker {
#Override
public void startWork() {
System.out.println("QA start Work");
}
#Override
public void endWork() {
}
}
I open the Developer class and trying to find usages of startWork().
I want only to view usage of the Developer.startWork() implemented method.
But when I find usages it shows both Developer and Qa.startWork() method usages. How can I avoid Qa.startWork() method usage when finding Developer.startWork() usages?
Using Ctrl+Shift+Alt+F7 (⌘+⇧+⌥+F7 for Mac) should show the prompt from Jim Hawkins answer.
See: https://www.jetbrains.com/help/idea/find-usages-method-options.html
When you search for usages of a method implementation with this dialog Ctrl+Shift+Alt+F7, IntelliJ IDEA will ask whether or not you want to search for the base method. With any other find usages actions such as Alt+F7 or Ctrl+Alt+F7, the base method will be included in the search results automatically.
I'm using IntelliJ IDEA 15.0.1 .
I think what you see when using the "find usages" functionality depends from the context.
If you place the cursor in method name Developer.startWork and invoke find usages , you should see a small dialog. You are asked "Do you want to find usages of the base method?" .
If you say "No", and in your sources you did only call the method via the base class or interface (Worker.start() in your example), IDEA doesn't show you any hits. Thats correct.
If you call the overridden method via Developer.startWork() , and press "No" in the dialog, then you will see the usages of the specific implementation.
Update:
After reading the answer from #JimHawkins, I think the elephant is still in the room :) The question is, do you want to see where Developer.startWork() is actually called, or do you want to see where it is statically referenced?
Eg:
Developer developer = new Developer();
developer.startWork(); // you want to find only this?
Worker worker = developer;
worker.startWork(); // ..or this as well?
The find usages method can only tell, where a given method is statically referenced, but not where it is actually used (that is determined runtime via the mechanism of polymorphism).

Unnecessary #SuppressWarnings("unused")

I'm getting a compiler warning for the #SuppressWarnings annotation in eclipse for the code:
#Override
public boolean doSomething(#SuppressWarnings("unused") String whatever) throws AnException {
throw new AnException("I'm still in bed and can't do anything until I've had a shower!");
}
It looks like a yellow squiggle under the word "unused" and on mouse hover I get the tooltip Unnecessary #SuppressWarnings("unused").
I think another developer is being prompted to put in these annotations by eclipse and I'm basically being prompted to take them out. How can I configure eclipse to prompt me to put the #SuppressWarnings annotation in instead of it complaining about it?
If anyone would like to comment on best practice here then that would also be most welcome.
In the code in your question, the #SuppressWarnings("unused") annotation is unnecessary because the method is either overriding another method from a superclass or implementing an interface. Even if you don't actually use the whatever parameter it's mandatory to declare it, otherwise the #Override annotation will produce an error (you'd be changing the signature of the overridden method if you removed the parameter.)
In some older versions of Eclipse the code as shown would not cause a warning, but in more recent releases it does. I believe it's a valid warning, and I'd rather remove the #SuppressWarnings("unused") in this case.
Go to
Window → Preferences → Java → Compiler → Errors/Warnings → Annotations.
And select Ignore for Unused '#SuppressWarnings` token.
Alternatively, if you think it's more correct to delete the SuppressWarnings annotation:
Window -> Preferences -> Java -> Compiler -> Errors/Warnings -> Unnecessary code -> Value of parameter is not used
and select Ignore in overriding and implementing methods
In my code there's no inheritance defining the 3 methods with #SuppressWarnings("unused")
This code gives 'Unnecessary #SuppressWarnings("unused")' in Eclipse Juno (latest version), but if I remove the #SuppressWarnings("unused"), I get "Constructor/Method is never used" warnings in IntelliJ IDEA 11.1.3
The methods aren't directly used in the project, only by 3rd party products Jackson, JAXB & GSON, so IntelliJ is right, I would say ...
public class EmailUnsendable extends SkjemaError {
private NestedCommand command; // Can't be Command (interface) because of GSON!
#SuppressWarnings("unused") // Used by Jackson/JAXB/GSON
public EmailUnsendable() {
}
public EmailUnsendable(String referenceNumber, String stackTrace, NestedCommand command) {
super(referenceNumber, stackTrace);
this.command = command;
}
#SuppressWarnings("unused") // Used by Jackson/JAXB/GSON
public NestedCommand getCommand() {
return command;
}
#SuppressWarnings("unused") // Used by Jackson/JAXB/GSON
public void setCommand(NestedCommand command) {
this.command = command;
}
}
I believe this is an error in Eclipse.

Why I can't use Override annotations at Android?

I'm developing an app to android but I can't use the Override annotations. It keeps saying that the method must override a superclass method, which does. I'm using Java 1.7 and Android API 8 (2.2). Using Eclipse.
Any ideas?
EDIT:
Example
#Override
public int getCount() {
// TODO Auto-generated method stub
return this.data.size();
}
But the compiler don't let me use #Override, saying its not a superclass method. I'm exetending BaseAdapter.
You should be using java 1.6 when building android projects. Java 1.7 isn't compatible with the current set of Android tools. Change your projects to use 1.6 and this problem should go away
In eclipse:
Right click project -> properties -> Java Compiler -> switch all references to 1.7 to 1.6
You can use #Override annotation. If you get this error, it means you have a mistake in the prototype of the method, or you are not extending what you want to extend.
For example, on API level 8, the following will give you the error, as the method introduced in API 11:
#Override
public void startActivities (Intent[] intents){
}

Categories

Resources