Home >Java >javaTutorial >Detailed explanation of Java basic access permission examples

Detailed explanation of Java basic access permission examples

怪我咯
怪我咯Original
2017-06-26 11:39:571527browse

1. Review of access modifiers

==public: The classes, properties, and methods modified by it can not only be accessed across classes, but also across packages

==private: Can modify data members, constructors, methods, but cannot modify classes. The members modified by it can only be accessed by the class itself and cannot be accessed by subclasses

==protected: Can modify data members, constructors, and methods, but cannot modify classes. It can be accessed by members of this class, the same package, or its subclasses (if it is a subclass, it can cross packages)

==Default: No Add any modifier to only allow access in the same package

2. Code example

##

package dog;
public class Dog {
    // 公共的
    public void publicMethod() {
        System.out.println("publicMethod");
    }
    // 保护的
     protected void protectedMethod() { // 被声明为protected的方法,可以被子类继承
         System.out.println("protectedMethod");
     }

     // 默认的
     void defaultMethod() {
         System.out.println("defaultMethod");
     }

     // 私有的
     private void privateMethod() { // 这个方法只可以在类内部被调用
         System.out.println("privateMethod");
     }
 }

class T {
     public static void main(String[] args) {
         Dog d = new Dog(); // 可以访问
         d.publicMethod(); // 可以访问
         d.protectedMethod(); // 可以访问
         d.defaultMethod(); // 可以访问
         // d.privateMethod(); //私有的方法,不能被在类外访问
     }
 }

//在上例的基础上,演示跨包的情况
package cat; //和dog 包不在一起

import dog.Dog;

public class Cat {
    void test() {
        Dog dog = new Dog();

        dog.publicMethod(); // 可以
        // dog.protectedMethod(); 不可以
        // dog.privateMethod(); 不可以
        // dog.defaultMethod(); 不可以
    }
}

##
//在前例的基础上,演示子类中的访问情况
class NiceDog extends Dog {
    void test() {
        Dog dog = new Dog();
        dog.publicMethod(); // 可以
        protectedMethod(); // 被protected修饰的成员,可以被继承过来,并这样调用
        // dog.protectedMethod(); 不可以
        // dog.privateMethod(); 不可以
        // dog.defaultMethod(); 不可以

    }
}

The above is the detailed content of Detailed explanation of Java basic access permission examples. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn