Thursday, May 29, 2008

Access Modifiers

1. Is it a must for a abstract class to have a abstract method?

A: No!

All methods defined in interfaces are abstract.
All classes which have abstract method(s) must be declared abstract, but not vice versa.

2. What is modifier for the default constructor implicitly generated by Java compiler?

A: The default constructor implicitly generated by Java compiler should have the same accessibility as the class. i.e. public class will have a public default constructor, package "friendly" class will have package "friendly" constructor, unless you explicitly define it otherwise.See Package usage example for details.

3. Can one object access a private variable of another object of the same class?

A: Yes! One object can access a private variable of another object of the same class. The private field can be accessed from static method of the class through an instance of the same class too.Here is an example:

public class Test1 {
private int i;
Test1(int ii) {
i = ii;
System.out.println("Self: " + i);
// to avoid infinite recursion
if (i != 3) {
Test1 other = new Test1(3);
other.i++;
System.out.println("Other: " + other.i);
}
}

public static void main(String[] args) {
Test1 t = new Test1(5);

// The private field can be accessed from
// static method of the same class
// through an instance of the same class
System.out.println(t.i);
}
}

4. Several questions about static:

a) Can a static variable be declared within a method?
b) Can a static method contain an inner class?
c) Can a static method contain an static inner class?

A:

a) No, not in Java, but yes in C++
b) Yes
c) No
The simplest way to have your doubts clarified is to write a short program, then compile it to see the result. CODE, Code, code, ... please! An example here:

class Test {
void method() {
//static int i = 3; // not compilable
}
static void smethod() {
//static int i = 3; // not compilable
class local {
}
/* not compilable
static class slocal {
}
*/
}
}

5. Why the following code not compilable? Do we need to initial final variable explicitly?

public class Test{
static int sn;
int n;
final static int fsn;
final int fn;
}

A:

The above code is not compilable since final variable fsn and fn are not initialized.Yes, final variable (variables), static or instance, must be initialized explicitly. It can be done by an initializer, static or instance respectively. final instance variables can also be initialized by every constructor.Three choices to make the code right:

public class Test{
static int sn;
int n;
final static int fsn = 3;
final int fn = 6;
}

public class Test{
static int sn;
int n;
final static int fsn;
final int fn;

static {fsn=6;}
{fn =8;}
}

public class Test{
static int sn;
int n;
final static int fsn;
final int fn;

static {fsn=6;}

Test(){
fn =8;
}
Test(int pn){
fn =pn;
}
}

6. Can we declare an object as final? I think I still can change the value of a final object.

A:

final variables cannot be changed.
final methods cannot be overridden.
final classes cannot be inherited. However, there is something easily to be confused. There is no final Object in Java. You cannot even declare an Object in Java, only Object references. We only can have final object reference, which cannot be changed. It is like that the address of your house cannot be changed if it is declared as final. However, you can remodel your house, add a room, etc. Your house is not final, but the reference to your house is final. That is a little confusing. By the way, use finals as much as possible, but do not overuse them of course. It is because compiler knows they are not going to change, the byte code generated for them will be much more efficient.

7. Can we use transient and static to modify the same variable? Does it make any difference in Object serialization?

A: Yes, we can use transient and static to modify the same variable. It Does not make any difference in Object serialization. Since both transient and static variables are not serializable.See your exausting example at TestSerialization.java

8. What happens if we don't declare a constructor as public? Is it a useful strategy somewhere?

A: Following discussion is based on the assumption of that your class is declared as public and at least has some public members, and the other package imports your class or using full-qualified names to use your class.

  1. You cannot construct an instance of the class by using this constructor in another package.

  2. If you have other constructors declared public, you still can construct an instance of the class by using other public constructors in another package.

  3. If all your constructors are not public, then the class cannot be constructed in packages other than the package it was defined.

  4. If the other package gets a reference to it, its public members still can be used. Singleton Design Pattern is a good example for it. We even use private construtor intentionally.

9. In a non-static inner class, static final variables are allowed, but not static variables! why?

A: When a variable is static final, actually, it is not a variable; it is a constant. Compiler will treat it differently.

10. Can final and transient be used together? Why?

A: Yes, they can.

final variables cannot be changed.
final methods cannot be overridden.
final classes cannot be inherited. transient variables cannot be serialized. They are independent of each other. A variable can be final or a constant (an oxymoron, right? ), and transient or not serializable. I actually figured out a good reason not to serialize final variables.Serializing objects are mostly for transferring data. The both side of transferring will know the Class object, know the constants in most of the cases, with the exception of initialized finals in constructors by using the parameter value. Not Serializing the final will certainly save transferring time. Using final and transient together will certainly have some advantages in distributed computing. And, please remember, putting final and transient together is an option, not a requirement.

11. Why null variable can access static member variables or methods?

A: When you call a static data member or method, all it matters is right type. See example here

// ST.java
class ST {
static int n = 3;
static int getInt() {
return n + 35;
}

public static void main(String[] args) {
ST st = null; // st has the type of ST

System.out.println(st.n); // 3
System.out.println(st.getInt());// 38

// the above lines are equivalent to the followings
System.out.println(ST.n); // 3
System.out.println(ST.getInt());// 38
}
}

12. Should we hide private method defined in the superclass by defining the same name and signature method in the subclass?

A: No.

If super class defined a private method, it hides itself; nobody else can see it or use it. That is exactly what private means. It does not need a subclass to define a same name and signature method to be hided!!!If the subclass use the same name and signature to define another method, it does not hide anything, it is just itself and totally irrelevant with the super class same name method. In addition, it should be only considered a bad-coding style, even it is legal.Please read everything about hiding here!
a section in JLS2

13. Why I got IllegalAccessException when I try to use reflection or dynamic proxy to access some package level methods from another package?

A: Why not?

Do you think what you get is the reasonable behavior of Java? OR Do you assume Proxy or reflection should break the rule of Java, and open a backdoor to a class, and let it do something, which it is not supposed to do?

No comments: