IB D3.3Define the terms: private, protected, public, extends, static

IB D3.3Define the terms: private, protected, public, extends, static_第1张图片

 Access modifiers

• Access level modifiers determine whether other classes can use a particular field or invoke a particular method.

访问级别修饰符决定其他类是否可以使用特定的字段或调用特定的方法。

• A class may be declared with the modifier public, in which case that class is visible to all classes everywhere.

• If a class has no modifier (i.e. the default position) it is visible only within its own package. • There are three Java access modifiers:

– public – protected – private

Definition: public

• A class, method, field or constructor that is declared public can be accessed from any other class.

• Therefore, fields, methods, blocks declared inside a public class can be accessed from any class belonging to the Java Universe.

• Because of class inheritance, all public methods and variables of a class are inherited by its subclasses.

Definition: private

• Methods, variables, and constructors that are declared private can only be accessed within the declared class itself.

• private is the most restrictive access level.

• Classes cannot be private, but methods and variables can.

• Variables that are declared private can be accessed outside the class, if public getter methods are present in the class.

• Using the private modifier is the main way that an object encapsulates itself and hides data from the outside world.

Definition: protected

• Variables, methods, and constructors, which are declared protected in a superclass can be accessed only by the subclasses in any class within the package of the protected members' class.

• protected cannot be applied to classes.

• protected access gives the subclass a chance to use the helper method or variable, while preventing a nonrelated class from trying to use it.

你可能感兴趣的:(java,开发语言)