Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement a final class without the "final" keyword

Tags:

java

A friend of mine was asked that question in his on-phone job interview a couple of days a go. I don't have a clue. can anyone suggest a solution? (His job interview is over. just out of curiosity now ) 10x.

like image 301
Bick Avatar asked Mar 23 '11 09:03

Bick


People also ask

How can we make a class final without using final keyword?

You can make your class immutable without using final keyword as: Make instance variable as private. Make constructor private. Create a factory method which will return the instance of this class.

How do you implement final class?

A class can be made final by using the final keyword. The final class cannot be inherited and so the final keyword is commonly used with a class to prevent inheritance.

Can final class have non final methods?

Hence, a final class cannot contain abstract methods whereas an abstract class can contain a final method.

Can we implement final class in Java?

The main purpose of using a class being declared as final is to prevent the class from being subclassed. If a class is marked as final then no class can inherit any feature from the final class. You cannot extend a final class.


1 Answers

  • Mark constructor as private
  • Provide a static method on the class to create instance of a class. This will allow you to instantiate objects of that class
like image 119
byte Avatar answered Oct 12 '22 12:10

byte