Java Reference
In-Depth Information
// Constructor #2 - public access level
public Test(int x) {
}
// Constructor #3 - private access level
private Test(int x, int y) {
}
// Constructor #4 - protected access level
protected Test(int x, int y, int z){
}
}
The effect of these access levels is the same as their effect for a method. A constructor with a public access level
can be used in any part of the program. A constructor with private access level can be used only inside the same class
in which it is declared. A constructor with protected access level can be used in any part of the program in the same
package in which its class is declared and inside any descendant class in any package. A constructor with package-
level access can be used inside the same package in which its class is declared.
You can specify public or package-level access level for a class. A class defines a new reference type, which you
can use to declare a reference variable. The access level of a class determines in which part of the program the name
of the class can be used. Usually, you use the name of a class in a cast or in a reference variable declaration as shown:
// Test class name is used to declare the reference variable t
Test t;
// Test class name is used to cast the reference variable xyz
Test t2 = (Test)xyz;
Let's discuss the different combinations of access levels for a class and its constructor, and its effects in a
program. Consider the following code that declares a class T1 with public access level and it has a constructor, which
also has a public access level:
// T1.java
package com.jdojo.cls.p1;
public class T1 {
public T1() {
}
}
Because the class T1 has a public access level, you can declare a reference variable of type T1 as shown below
anywhere in the program:
// Code inside any package
T1 t;
Because the constructor for the class T1 has a public access level, you can use it in an object creation expression
in any package.
// Code inside any package
new T1();
 
Search WWH ::




Custom Search