This is some information on the Java 6 certification that I prepare. This information is not very well structured and it is most of the time an answer to the questions that come when I read the SCJP 6 book (Bates and Sierra). *** AS OF 5 OF MARCH 2010, I AM SCJP 6.0 ***

Wednesday, January 6, 2010

4 - classes public or not ?

What is the difference between a public class and a non public class. Why should I make my class public ?

IMHO the answer is related to the reusability of components. If the class is NOT public you cannot access any of its members outside of its own package !!!

It is important to notice that if a class is NOT public, even if you make the member of the class public, the member will not be accessible !!! The compiler will first check the visibility of the class and then the member !!!

So if you design a class only to be used within its own package there is no need to make it seen to the outside world (the other packages).

Example :

package test;
class Class1 {
    public static int version=1001;
    void method1() {
        System.out.println("method1");
    }
}

package qa;
class Class2 {
    public static void main(String[] args) {
        System.out.println("Hello !");
        System.out.println("version : " + test.Class1.version);
     }
}

rudy@vsolutions:~/Documents/SCP6/CH1$ javac -cp . qa/Class2.java
qa/Class2.java:10: test.Class1 is not public in test; cannot be accessed from outside package
        System.out.println("version : " + test.Class1.version);
                                              ^
1 error


As you can see "version" is public but cannot be used in qa !

Could you notice the following : Netbeans will always make your classes public by default.

No comments:

Post a Comment

Followers