Java overriding methods when creating new instance of a class - java

This might be simple for seasoned java developers but I just cant seem to figure it out. I read a post from here. The code was
View v = new View(this) {
#Override
protected void onDraw(Canvas canvas) {
System.out.println("large view on draw called");
super.onDraw(canvas);
}
};
It was an Android question. Here the user creates an instance of a view and overrides a method in a single line. Is there a name for this kind of coding?
My second doubt is, he overrides a protected method from another package. Isn't protected mean package private. I know this will work as I tried it out but I just couldn't figure out why it worked. So why is this code working?
I did try to google this and search in SO before asking but couldn't figure out an answer.

protected means (roughly) "available to sub-classes". (See this table.) Since the new View(this) { ... } creates a subclass, it is possible to override the method within it.
In this case it doesn't matter that you're in a different package. (See the protected line and second column in this table.) The fact that the method is in a subclass is sufficient to "get access" to a protected method.
Potential follow-up question: What sense does it make, if I can't call the method anyway?
All methods in Java are virtual. This means that whenever the View class performs a seemingly internal call to the onDraw method, this call will be dispatched to the overridden method.

That is not exactly a kind of coding. That is a Java anonymous class. It is very common in Android and in general with event listeners and that kind of stuff.
For more details you can read this link (probably not the best one):
The anonymous inner classes is very useful in some situation. For
example consider a situation where you need to create the instance of
an object without creating subclass of a class and also performing
additional tasks such as method overloading.
About your second question, the keyword protected means that the method is only available to subclasses, so it is possible to override the method.

This is an anonymous class. You are correct that you are overriding a protected method and this is perfectly normal. A protected method is visible, and can therefore be overridden, by a sub class, which is what you have created here.
Package protected is the default scope when you do not provide a scope for your variable or method. That is different to protected.

So many answeres were there for "protected", so i am going to other one :)
#override is informing the compiler to override the base class method, and if there is no base class method of this signature then throws compilation error.
These are called annotations. You can search for annotations topic in java. You can create custom annotations as well.
Regards,
SSuman185

Just like others here are already answered this is called anonymous class, and overriding protected methods is legal since protected methods are visible to child classes and classes in same package.

Related

Unable to access protected final synchronized method in a class

This may be a silly question as I am new to android programming. I have imported a .aar library in my android project where I am trying to access a protected final synchronized method in one of the class present in that library. However, I am able to refer other methods present in the class which are not synchronized/final. When I open the source of the library from which I created the .aar file, I am able to see the method but unable to use it after importing it.
Can you please tell what is going wrong here?
Importing has nothing to do with accessibility and visibility of fields and methods of the imported class, it is just a shortcut for not typing the full class name every time you use the class.
To access an imported method or field of a certain class, the modifier preceding them should be marked as public.
Since the method you tried to access is marked as protected, the method can be accessed only if you are trying to access it within the subclass that extended class BaseActivity, or if you are accessing it from the class of the same package.
The solution is to extend the BaseActivity and either use the method within your customized method like this:
public class SomeOtherActivity extends BaseActivity{
public void someOtherMethod(Runnable task, long delayMillis){
super.queueEvent(task,delayMills);
}
}
This way the method you declared provides a public interface to other developers that wants to use your specific version of method that queues events.
However, this is not done through polymorphism nor with composition, so you might have to make sure that you really need this method or if there's another existing solution, since there's a reason that the original method is marked as final and protected which might cause other problems if not dealt with care.
Introduction to access modifiers can be found here:
The Java tutorials - Controlling Access to Members of a Class
On the other hand, this problem has nothing to do with "synchronized" and "final"
Introduction for the keyword synchronized can be found here:
The Java tutorials - Synchronized Methods
Introduction for the keyword final can be found here:
The Java tutorials - Final Classes and Methods
When you say "use" do you mean call/invoke or override?
A. protected methods are only visible to the package and subclasses
B. final methods cannot be overridden
With A and B the only thing you can do with that method is call it in your subclass.
Protected methods can be called only by classes that extend the main class.
To bypass this error that you are getting, you can create a class that extends your BaseActivity class and then a public method that calls the private one.
Something like this:
class MyBaseActivity extends BaseActivity {
public final synchronized void myQueueEvent(Runnable task, long delayMillis) {
super.queueEvent(task, delayMillis);
}
}
Now you can use it by calling: MyBaseActivity.myQueueEvent(...);

Why Lint give an advice to make my constructor protected for abstract class?

I'm wondering what is behind the Lint's advice of making the constructor of an abstract class protected?
Non-child classes can't call the constructor of an abstract class (it's not possible). The only classes that can call that constructor are children of the abstract class. Setting the constructor as protected only allows child classes to see the constructor.
Edit: For more information, see this question.
Also, Joop is correct about anonymous implementations (I didn't even know you could do that in Java). However, I have never seen anyone do that.
Seemingly to prevent anonymous implementations:
new AbstractClass() { ... };

Overriding specific lines from a parent class

I have a class Writer which has a method process(). A subclass, TextWriter, extends Writer.
I want to use the method process() of the parent class, except for the last line of the method, which I want to customize according to the needs of the subclass.
Is there any way I can call super() in such a way that I can inherit only specific parts of the parent class's method?
I know this is bad design, and in such cases interfaces must be used. But I was working on making some changes on some old code, and I was wondering if it is possible to do this.
You should put the joint code in a protected method and have the process method call it, like:
public class Writer {
protected void process_subProcess(){
//most of process code
}
public void process(){
process_subProcess();
//specific last line
}
}
Then TextWriter only overrides the bit it needs to. subProcess isn't a great name, consider a better one depending on what the subProcess actually does
public class TextWriter extends Writer{
#Override
public void process(){
process_subProcess();
//different final line
}
}
The joint code is protected so that child classes can access it but you can't accidentally use the subProcess method from outside the package
No, this is not possible in Java.
If you have control over the parent class, you can refactor it to ensure the relevant parts can be overriden. If not, you don't really have another option.
No, but you can extract the part that differes between both classes to another methode which you implement differently in each class.
No, You cann't override a certain piece of code. overriding is related to the method not to some line of code
No you can't do that.
Best way is override that method in your child class and do your specific work.

How to cause a compile error/warning, when a protected (or abstract) method in the parent class is removed and sub-classes have implemented it

Let's say you you have a class called Vehicle that outlines a protected (could also be abstract) method called speed. And, the sub class Car overrides that method to define its own implementation.
Now, assume that the need to have a speed method in the Vehicle class is no longer required (let's say all vehicles will be stationary for the whatever reason).
If I remove the method speed from Vehicle, I would like to throw a compile error so that so that the developer who has removed the method knows that sub class(es) are potentially relying on it to perform certain actions.
Technically speaking a compile error is not needed, but some sort of notification that acts as a hurdle when such re factoring is happening. Is there a programming pattern that can be employed to handle such a situation?
UPDATE: I am using Java 1.4 (Sorry!)
The #Override annotation is expressly for this purpose.
If you're not using Java 1.5+, then no, although you could use AOP to instrument those methods to throw an exception, or just use reflection and classpath scanning to go over all subclasses and check for the presence of said method.
If it's abstract, then there is no implementation that can be removed from the parent class, and your risk comes down to new subclasses not implementing it. If it's protected and defined in the parent, there are two cases that should already throw compiler errors if the parent implementation is removed.
1) A subclass calls that method without defining its own implementation. Method does not exist.
2) A subclass defines the method, but includes a call to super. Again, the method does not exist.
You can write super.speed() in nested classes and leave this method empty in parent. If you delete now this method in parent, you'll have an Exception. But there is a disadvantage - you must call it from all overrided methods. Try it, perhaps this will help you
Use #Override annotation for methods in subclases.
Once you remove the method from a base-class, tools like Eclipse and javac will issue a warining for those no-longer-overriding methods.
Edit: While you cannot use #Override before Java 1.5.0, there is a tool called xdoclet. Back in the days of J2EE and EJB 2.1 this was used to "simulate" annotations and do magical things with code based on javadoc-like markers. Look at it, maybe you can use it.
Edit 2: In Java 1.4.x, you can also use JavaDoc tag {#inheritDoc} for this kind of verification. Instead of annotating your method with #Override annotate it with #inheritDoc, like this:
public class MyAwesomeClass extends BaseClass
{
/** {#inheritDoc} */
protected void myAweSomeMethod()
{
//...
}
}
Now, if you change the myAweSomeMethod signature in BaseClass, or remove it, you will get warnings from JavaDoc tool, similar to this:
/home/npe/java-tests/MyAwesomeClass.java:4: warning - #inheritDoc used but myAwesomeMethod does not override or implement any method.

When do you use Java's #Override annotation and why?

Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
What are the best practices for using Java's #Override annotation and why?
It seems like it would be overkill to mark every single overridden method with the #Override annotation. Are there certain programming situations that call for using the #Override and others that should never use the #Override?
Use it every time you override a method for two benefits. Do it so that you can take advantage of the compiler checking to make sure you actually are overriding a method when you think you are. This way, if you make a common mistake of misspelling a method name or not correctly matching the parameters, you will be warned that you method does not actually override as you think it does. Secondly, it makes your code easier to understand because it is more obvious when methods are overwritten.
Additionally, in Java 1.6 you can use it to mark when a method implements an interface for the same benefits. I think it would be better to have a separate annotation (like #Implements), but it's better than nothing.
I think it is most useful as a compile-time reminder that the intention of the method is to override a parent method. As an example:
protected boolean displaySensitiveInformation() {
return false;
}
You will often see something like the above method that overrides a method in the base class. This is an important implementation detail of this class -- we don't want sensitive information to be displayed.
Suppose this method is changed in the parent class to
protected boolean displaySensitiveInformation(Context context) {
return true;
}
This change will not cause any compile time errors or warnings - but it completely changes the intended behavior of the subclass.
To answer your question: you should use the #Override annotation if the lack of a method with the same signature in a superclass is indicative of a bug.
There are many good answers here, so let me offer another way to look at it...
There is no overkill when you are coding. It doesn't cost you anything to type #override, but the savings can be immense if you misspelled a method name or got the signature slightly wrong.
Think about it this way: In the time you navigated here and typed this post, you pretty much used more time than you will spend typing #override for the rest of your life; but one error it prevents can save you hours.
Java does all it can to make sure you didn't make any mistakes at edit/compile time, this is a virtually free way to solve an entire class of mistakes that aren't preventable in any other way outside of comprehensive testing.
Could you come up with a better mechanism in Java to ensure that when the user intended to override a method, he actually did?
Another neat effect is that if you don't provide the annotation it will warn you at compile time that you accidentally overrode a parent method--something that could be significant if you didn't intend to do it.
I always use the tag. It is a simple compile-time flag to catch little mistakes that I might make.
It will catch things like tostring() instead of toString()
The little things help in large projects.
Using the #Override annotation acts as a compile-time safeguard against a common programming mistake. It will throw a compilation error if you have the annotation on a method you're not actually overriding the superclass method.
The most common case where this is useful is when you are changing a method in the base class to have a different parameter list. A method in a subclass that used to override the superclass method will no longer do so due the changed method signature. This can sometimes cause strange and unexpected behavior, especially when dealing with complex inheritance structures. The #Override annotation safeguards against this.
To take advantage from compiler checking you should always use Override annotation. But don’t forget that Java Compiler 1.5 will not allow this annotation when overriding interface methods. You just can use it to override class methods (abstract, or not).
Some IDEs, as Eclipse, even configured with Java 1.6 runtime or higher, they maintain compliance with Java 1.5 and don’t allow the use #override as described above. To avoid that behaviour you must go to: Project Properties ->Java Compiler -> Check “Enable Project Specific Settings” -> Choose “Compiler Compliance Level” = 6.0, or higher.
I like to use this annotation every time I am overriding a method independently, if the base is an interface, or class.
This helps you avoiding some typical errors, as when you are thinking that you are overriding an event handler and then you see nothing happening. Imagine you want to add an event listener to some UI component:
someUIComponent.addMouseListener(new MouseAdapter(){
public void mouseEntered() {
...do something...
}
});
The above code compiles and run, but if you move the mouse inside someUIComponent the “do something” code will note run, because actually you are not overriding the base method mouseEntered(MouseEvent ev). You just create a new parameter-less method mouseEntered(). Instead of that code, if you have used the #Override annotation you have seen a compile error and you have not been wasting time thinking why your event handler was not running.
#Override on interface implementation is inconsistent since there is no such thing as "overriding an interface" in java.
#Override on interface implementation is useless since in practise it catches no bugs that the compilation wouldn't catch anyway.
There is only one, far fetched scenario where override on implementers actually does something: If you implement an interface, and the interface REMOVES methods, you will be notified on compile time that you should remove the unused implementations. Notice that if the new version of the interface has NEW or CHANGED methods you'll obviously get a compile error anyways as you're not implementing the new stuff.
#Override on interface implementers should never have been permitted in 1.6, and with eclipse sadly choosing to auto-insert the annotations as default behavior, we get a lot of cluttered source files. When reading 1.6 code, you cannot see from the #Override annotation if a method actually overrides a method in the superclass or just implements an interface.
Using #Override when actually overriding a method in a superclass is fine.
Its best to use it for every method intended as an override, and Java 6+, every method intended as an implementation of an interface.
First, it catches misspellings like "hashcode()" instead of "hashCode()" at compile-time. It can be baffling to debug why the result of your method doesn't seem to match your code when the real cause is that your code is never invoked.
Also, if a superclass changes a method signature, overrides of the older signature can be "orphaned", left behind as confusing dead code. The #Override annotation will help you identify these orphans so that they can be modified to match the new signature.
If you find yourself overriding (non-abstract) methods very often, you probably want to take a look at your design. It is very useful when the compiler would not otherwise catch the error. For instance trying to override initValue() in ThreadLocal, which I have done.
Using #Override when implementing interface methods (1.6+ feature) seems a bit overkill for me. If you have loads of methods some of which override and some don't, that probably bad design again (and your editor will probably show which is which if you don't know).
#Override on interfaces actually are helpful, because you will get warnings if you change the interface.
Another thing it does is it makes it more obvious when reading the code that it is changing the behavior of the parent class. Than can help in debugging.
Also, in Joshua Block's book Effective Java (2nd edition), item 36 gives more details on the benefits of the annotation.
It makes absolutely no sense to use #Override when implementing an interface method. There's no advantage to using it in that case--the compiler will already catch your mistake, so it's just unnecessary clutter.
Whenever a method overrides another method, or a method implements a signature in an interface.
The #Override annotation assures you that you did in fact override something. Without the annotation you risk a misspelling or a difference in parameter types and number.
I use it every time. It's more information that I can use to quickly figure out what is going on when I revisit the code in a year and I've forgotten what I was thinking the first time.
The best practive is to always use it (or have the IDE fill them for you)
#Override usefulness is to detect changes in parent classes which has not been reported down the hierarchy.
Without it, you can change a method signature and forget to alter its overrides, with #Override, the compiler will catch it for you.
That kind of safety net is always good to have.
I use it everywhere.
On the topic of the effort for marking methods, I let Eclipse do it for me so, it's no additional effort.
I'm religious about continuous refactoring.... so, I'll use every little thing to make it go more smoothly.
Used only on method declarations.
Indicates that the annotated method
declaration overrides a declaration
in supertype.
If used consistently, it protects you from a large class of nefarious bugs.
Use #Override annotation to avoid these bugs:
(Spot the bug in the following code:)
public class Bigram {
private final char first;
private final char second;
public Bigram(char first, char second) {
this.first = first;
this.second = second;
}
public boolean equals(Bigram b) {
return b.first == first && b.second == second;
}
public int hashCode() {
return 31 * first + second;
}
public static void main(String[] args) {
Set<Bigram> s = new HashSet<Bigram>();
for (int i = 0; i < 10; i++)
for (char ch = 'a'; ch <= 'z'; ch++)
s.add(new Bigram(ch, ch));
System.out.println(s.size());
}
}
source: Effective Java
Be careful when you use Override, because you can't do reverse engineer in starUML afterwards; make the uml first.
It seems that the wisdom here is changing. Today I installed IntelliJ IDEA 9 and noticed that its "missing #Override inspection" now catches not just implemented abstract methods, but implemented interface methods as well. In my employer's code base and in my own projects, I've long had the habit to only use #Override for the former -- implemented abstract methods. However, rethinking the habit, the merit of using the annotations in both cases becomes clear. Despite being more verbose, it does protect against the fragile base class problem (not as grave as C++-related examples) where the interface method name changes, orphaning the would-be implementing method in a derived class.
Of course, this scenario is mostly hyperbole; the derived class would no longer compile, now lacking an implementation of the renamed interface method, and today one would likely use a Rename Method refactoring operation to address the entire code base en masse.
Given that IDEA's inspection is not configurable to ignore implemented interface methods, today I'll change both my habit and my team's code review criteria.
The annotation #Override is used for helping to check whether the developer what to override the correct method in the parent class or interface. When the name of super's methods changing, the compiler can notify that case, which is only for keep consistency with the super and the subclass.
BTW, if we didn't announce the annotation #Override in the subclass, but we do override some methods of the super, then the function can work as that one with the #Override. But this method can not notify the developer when the super's method was changed. Because it did not know the developer's purpose -- override super's method or define a new method?
So when we want to override that method to make use of the Polymorphism, we have better to add #Override above the method.
I use it as much as can to identify when a method is being overriden. If you look at the Scala programming language, they also have an override keyword. I find it useful.
It does allow you (well, the compiler) to catch when you've used the wrong spelling on a method name you are overriding.
Override annotation is used to take advantage of the compiler, for checking whether you actually are overriding a method from parent class. It is used to notify if you make any mistake like mistake of misspelling a method name, mistake of not correctly matching the parameters
i think it's best to code the #override whenever allowed. it helps for coding. however, to be noted, for ecipse Helios, either sdk 5 or 6, the #override annotation for implemented interface methods is allowed. as for Galileo, either 5 or 6, #override annotation is not allowed.
Annotations do provide meta data about the code to the Compiler and the annotation #Override is used in case of inheritance when we are overriding any method of base class. It just tells the compiler that you are overriding method. It can avoide some kinds common mistakes we can do like not following the proper signature of the method or mispelling in name of the method etc. So its a good practice to use #Override annotation.
For me the #Override ensures me I have the signature of the method correct. If I put in the annotation and the method is not correctly spelled, then the compiler complains letting me know something is wrong.
Simple–when you want to override a method present in your superclass, use #Override annotation to make a correct override. The compiler will warn you if you don't override it correctly.

Categories