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.
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 ***
Subscribe to:
Post Comments (Atom)
Followers
Blog Archive
-
▼
2010
(38)
-
▼
January
(29)
- 28 - Review - xxxValue() - parseXxx() - valueOf()...
- 27 - Review - type of an array - level basic - Jav...
- 26 - Review - protected - level basic - Java 1.6.0...
- 25 - Review - private - level basic - Java 1.6.0_1...
- 24 - Thread : notify/notifyall- level basic - Java...
- 23 - Thread : deadlock - level basic - Java 1.6....
- 22 - Thread : same or different object ? - level ...
- 21 - example of Thread.join - level basic - Java ...
- 20 - non public class and public method - level ve...
- 19 - hashCode - level basic - Java 1.6.0_17 - NB 6.8
- 18 - Sorted Sets and a strange class - level basic...
- 17 - Arrays.sort example - level basic - Java 1.6....
- 16 - Comparable and Comparator - level basic - Ja...
- 15 - two ways to compare - level basic - Java 1.6....
- 14 - RegExp
- 13 - Example with transient (3)
- 12 - Example with transient (2)
- 11 - Example with transient (1)
- 10 - Netbeans does not seem to do anything !
- 9 - Local conversions
- 8 - Abstract classes and static methods
- 7 - Object Creation
- 0 - ERRATA - SCJP Sun Certified Programmer for Jav...
- 6 - visibility of interfaces and classes
- 5 - short and char
- 4 - classes public or not ?
- 3 - Forcing to catch Error
- 2 - Numerics
- 1 - Scope
-
▼
January
(29)
No comments:
Post a Comment