Posts

Showing posts from January, 2011

Java Puzzle – Variable Declaration

In Java, how will you declare a variable x such that the following two conditions are satisfied? 1.     x = ++x  is valid 2.     x = x + 1 is invalid          Leave your code in Comments ... 

Non-extendable Class

First thing comes in mind when somebody say Non-extendable class , that is final class. Marking a class as “final” , no one can extends the particular class. But there is another tricky way to restricting any other class from extending your class. Thinking how ….? Simple, marking all available constructors of  a class as private. As per constructor chaining principle in class hierarchy , every child class constructor should delegate call to super class explicitly or implicitly. In implicit case, call get delegate to class’s default constructor. If all available constructors of the class are private then no other class can not extend it. 1: public class MyClass { 2: 3: private MyClass(){ 4: System.out.println(" Inside Singleton Constructor "); 5: } 6: 7: } 8: 9: class MyChildClass extends MyClass{ // compilation error 10: 11: }