blessenm blessenm - 1 year ago 63
Java Question

Java overriding methods when creating new instance of a class

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) {
protected void onDraw(Canvas canvas) {
System.out.println("large view on draw called");

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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download