Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Final classes in Java which shouldn't be final or vice versa?

Tags:

java

class

final

I was asked this question in an interview recently:

Can you name any class in the Java API that is final that shouldn't be or one that isn't and should be'?

I couldn't think of any. The question implies that I should know all the API classes like the back of my hand, which I personally wouldn't expect any Java developer to know.

If anyone knows any such classes, please provide examples.

like image 267
sotn Avatar asked Feb 04 '13 10:02

sotn


People also ask

Can final class have non final methods?

In effect, yes it does. A method in a final class cannot be overridden.

Can Java classes be final?

You can declare some or all of a class's methods final. You use the final keyword in a method declaration to indicate that the method cannot be overridden by subclasses. The Object class does this—a number of its methods are final .

Can abstract classes be final?

Abstract classes are similar to interfaces. You cannot instantiate them, and they may contain a mix of methods declared with or without an implementation. However, with abstract classes, you can declare fields that are not static and final, and define public, protected, and private concrete methods.

Is final class Cannot be overridden?

No, the Methods that are declared as final cannot be Overridden or hidden. For this very reason, a method must be declared as final only when we're sure that it is complete.


1 Answers

java.awt.Dimension isn't final or immutable and should have been. Anything that returns a Dimension (e.g a Window object) needs to make defensive copies to prevent callers from doing nasty things.

like image 109
Michael Barker Avatar answered Oct 11 '22 14:10

Michael Barker