12

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.

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
Bick
  • 17,833
  • 52
  • 146
  • 251
  • 4
    If I were answering that interview question, I'd like to say, *"If I wanted a `final` class, I'd use the flippin' `final` keyword. It's there for a reason."* I understand that they're probably trying to glean something about the interviewee's creativity, but there are better ways than asking about how someone might avoid using a language to it's fullest capability. – Rob Hruska Mar 23 '11 at 11:01
  • @Rob: I'd consider that *part* of the question, myself. A good chunk of the answer is the techniques below, but if a candidate was able to say "of course, this gives the 'can't extend' semantics of final classes, but since they're not technically final there are some optimisations that HotSpot might not realise it could do, ... etc." then surely that's bonus marks as well. Both parts show knowledge of the relevance of `final`, and the latter shows awareness and a sense of "good" and "bad" vs. merely "functionally correct" code. – Andrzej Doyle Mar 23 '11 at 11:11
  • @Andrzej Doyle - Point taken. I guess it depends on the interviewer and how they're approaching the question. My comment was somewhat knee-jerk, I suppose. – Rob Hruska Mar 24 '11 at 12:29

7 Answers7

12
  • 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
byte
  • 1,665
  • 1
  • 19
  • 36
  • 1
    And if you want to be safe from unsafe publication, mark your fields `volatile`. – Tom Hawtin - tackline Mar 23 '11 at 11:05
  • Is there any extra benifits it has when final keyword is used with proposed two lines.? @byte – Gnanz May 26 '11 at 06:34
  • 1
    Correct but this will only prevent object creation. But final class can't be **overridden**,so question is how to prevent inheritance? **How to stop class being inherited(without using final)?** – Nishant Shah Apr 26 '14 at 07:22
0

Make all the constructors of that class as private to stop inheriting, Though not recommended.

user1923551
  • 4,684
  • 35
  • 29
0
public class Immutable {       
    private int val;

    public Immutable(int v)
    { 
        this.val = v;
    }

    public int getVal() { return this.val; }
}
justanothercoder
  • 1,830
  • 1
  • 16
  • 27
Vickal
  • 161
  • 1
  • 8
0

I don't know what they mean exactly mean by a final class. If they mean a class that cannot be extended by inheritence, than clearly this cannot be done, except by marking that class with final (or sealed, or whatever the language keyword is).

But if the mean final as in immutable, such that a derived class can't modify the value of the fields in the class,than the base class should have all of the fileds and accessor methods private.

Victor Blaga
  • 1,822
  • 4
  • 19
  • 28
  • 1
    "If they mean a class that cannot be extended by inheritence, than clearly this cannot be done, except by marking that class with final" - wrong. It can also be achieved by making the constructor(s) private. – Péter Török Mar 23 '11 at 09:42
0

Create a private constructor without parameters?

public class Base
{
    private Base()
    {
    }
}

public class Derived : Base
{
//Cannot access private constructor here error
}
illegal-immigrant
  • 8,089
  • 9
  • 51
  • 84
0

You can make your class immutable without using final keyword as:

  1. Make instance variable as private.
  2. Make constructor private.
  3. Create a factory method which will return the instance of this class.

I am providing immutable class here in Java.

class Immutable {
    private int i;
    private Immutable(int i){
     this.i = i;
    }
    public static Immutable createInstance(int i){
         return new Immutable(i);
    }
    public int getI(){return i;}
}
 class Main {
    public static void main(string args[]){
       Immutable obj = Immutable.createInstance(5);
    }
}
salman94
  • 60
  • 8
  • Some mistakes in your code. First - **createInstance** method is missing return type. And the biggest one - cannot use **this** in static context. And one from me - should try **equals**, not *this.i == i*. But this doesn't matter since **createInstance** method doesn't work. Anyway - good try. – Evgeni Enchev Sep 09 '19 at 07:38
  • Thanks for pointing out my mistakes. I have updated my code. @EvgeniEnchev – salman94 Sep 09 '19 at 08:44
-1

Static classes can't be inherited from

Xhalent
  • 3,914
  • 22
  • 21
  • you try and create a class that inherits from a static class. It can't be done. For all intents and purposes, the static class is final/sealed whatever. – Xhalent Mar 23 '11 at 09:41
  • `public class Test { static class A {} static class B extends A{} public static void main(String [] args) throws Exception { B b = new B(); System.err.println(""+b); } }` paste in `Test.java`, compile, and run, please. – khachik Mar 23 '11 at 09:43
  • "static classes" in a language that has `final`? Must be static nested classes, which can be extended. – Tom Hawtin - tackline Mar 23 '11 at 11:04