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 classAnimal
and a subclassDog
:
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
’sname
field uses theprotected
modifier, so ## The #Dogclass has access to it. The
eat()
Animaluses the
publicmodifier, so it can be called by both the
Dogclass and other classes it.
's
bark()method uses the
publicmodifier, 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!