Câu hỏi phỏng vấn Java
Câu hỏi

What is the difference between public , protected , package-private and private in Java?

Câu trả lời

In Java, access modifiers are keywords used to set the accessibility of classes, methods, and other members. They help in implementing encapsulation by controlling what parts of a program can access the members of a class. Here's a detailed explanation of each type of access modifier:

Public

The public access modifier allows the class, method, or field to be accessible from any other class or method anywhere in the application or from any other application that imports the class containing the public member. It offers the least restrictive access level. Using public makes a member universally available, which is particularly useful for elements that form the API of a library or module[1][2][3][4][5].

Protected

The protected access modifier restricts the access to the class, method, or field such that only the classes in the same package or subclasses (even if they are in different packages) can access the member. This modifier is more restrictive than public but less restrictive than package-private and private. It is typically used when you want to hide the member from the world but still allow its access by subclasses, which might be spread across different packages[1][3][4][5][6].

Package-Private (Default)

If no access modifier is specified, the default access is package-private, which means the class, method, or field is accessible only within the same package. It is more restrictive than protected and public but less restrictive than private. This level of access is used when you want to restrict usage to within the same group of closely related classes (i.e., those that share th...

middle

middle

Gợi ý câu hỏi phỏng vấn

junior

What will happen to the Exception object after exception handling?

senior

What does Connection Pooling mean?

junior

What are pass by reference and pass by value?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào