Access permission modifiers determine the access scope of classes, methods and fields, and play an important role in inheritance: public: Allow access to all classes and subclasses. protected: allows access by classes and their subclasses in the same package. default: Allow access to classes within the same package. private: Allows access only to the class itself that defines the modifier. A subclass cannot access the members of the parent class using the private modifier, but can change the value of the parent class member with the protected modifier. If you do not specify an access modifier, the member will default to default (package scope).
The relationship between access modifiers of Java functions and inheritance
The access modifiers in Java determine classes and methods and field access scope play an important role in inheritance. The following is the relationship between access modifiers and inheritance:
Practical case:
Suppose we have a parent class Animal
and a subclass Dog
:
public class Animal { protected String name; public void eat() { System.out.println("Eating..."); } } public class Dog extends Animal { public void bark() { System.out.println("Barking!"); } }
In the above code:
Animal
’s name
field uses the protected
modifier, so ## The #Dog class has access to it. The
eat()
Animal uses the
public modifier, so it can be called by both the
Dog class and other classes it.
's
bark() method uses the
public modifier, so any class can call it.
Note:
modifier.
modifier.
(package scope).
The above is the detailed content of The relationship between Java function access modifiers and inheritance. For more information, please follow other related articles on the PHP Chinese website!