Java Basics (b) public, private, protected modified method

Disclaimer: This article is a blogger original article, please indicate the source. Welcome to public concern number: Java Notes Share (xiaosen_javashare) https://blog.csdn.net/qq_36447151/article/details/80405950
 
 

GitHub: https://github.com/lgsdaredevil/keyWords.git

public: public, externally visible method

public void publicTest(){
        System.out.print("this is public method!\n");
    }

private: private, not externally visible, this method can only be called class

private void privateTest(){
        System.out.print("this is private method!\n");
    }

    public void getPrivate(){
        this.privateTest();
    }

protected: protected method, there is inheritance, the parent class method is protected, the parent can call their own, the subclass can call protected method of the parent class, non-inheritance is not visible

Father categories:

    protected void protectedTest(){
        System.out.print("this is father's protected method!\n");
    }

    private void privateFather(){
        System.out.print("this is father's private method!\n");
    }

    public void fatherTest(){
        this.privateFather();
        this.protectedTest();
    }

Child categories:

public void childTest(){
        System.out.print("this is child's method\n");
        super.protectedTest();
    }

main methods:

public static void main(String[] args){
        JavaPublic javaPublic = new JavaPublic();
        javaPublic.publicTest();
        JavaPrivate javaPrivate = new JavaPrivate();
        javaPrivate.getPrivate();
        Child child = new Child();
        child.childTest();
        // 父类对象引用子类不可以调用父类的protected方法
        Father father = new Child();
        father.fatherTest();
    }

Output:

to sum up:

public externally visible
external private non-visible, only this class calls
protected inheritance, the base class members also protected modified, derived classes can call the non-inheritance is not visible

Public personal number, share notes from time to time update, please pay attention

Guess you like

Origin blog.csdn.net/qq_36447151/article/details/80405950