Java学习——包及可见性

Posted 蔡军帅

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java学习——包及可见性相关的知识,希望对你有一定的参考价值。

 

1.在同一个类中:创建的对象,不管成员的可见修饰符可以直接调用。
package studentpackage;
public class Student {
    public long id;
    protected String name;
    private char sex;
    int age;

    public String toString() {
        return id + name + sex + age;
    }

    public static void main(String args[]) {
        Student s1 = new Student();
        s1.id = 20110010l;
        s1.name = "zhangshan";
        s1.sex = ‘M‘;
        s1.age = 20;
        System.out.println(s1);
    }
}
2.在同一个包中不同类中的可见性:私有不可见,其它都可见
//程序名为Student.java
package studentpackage;
public class Student {
    public long id;
    protected String name;
    private char sex;
    int age;

    public String toString() {
        return id + name + sex + age;
    }

//程序名为TestStudent.java
package studentpackage;
public class TestStudent {
    public static void main(String[] args) {
        Student s1=new Student();
        s1.id = 20110010l;
        s1.name = "zhangshan";
        s1.sex = ‘M‘;
        s1.age = 20;
        System.out.println(s1);
    }
}

3.在不同的包中:先注意类的可见性,可见后只有public成员可见
//程序名为Student.java
package studentpackage;
public class Student {
    public long id;
    protected String name;
    private char sex;
    int age;

    public String toString() {
        return id + name + sex + age;
    }

//程序名为 XueYuan.java
package studentpackage;
class XueYuan {
    Long xyid;
    String xyName;
    String xyweizhi;
    public XueYuan() {
    }

    public XueYuan(Long xyid, String xyName, String xyweizhi) {
        super();
        this.xyid = xyid;
        this.xyName = xyName;
        this.xyweizhi = xyweizhi;
    }

    public String toString() {
        return xyid + xyName + xyweizhi;
    }
}

//程序名为TestStudent_xueyuan.java
package teststudentpackage;
import studentpackage.*;
public class TestStudent_xueyuan {
    public static void main(String[] args) {
        Student s1=new Student();
        s1.id = 20110010l;
        s1.name = "zhangshan";
        s1.sex = ‘M‘;
        s1.age = 20;
        System.out.println(s1);
        XueYuan xy1=new XueYuan();//注意是否可行
    }
}

 

以上是关于Java学习——包及可见性的主要内容,如果未能解决你的问题,请参考以下文章

synchronized学习

Android:通过更改片段更改菜单项的可见性

显示/隐藏片段并以编程方式更改可见性属性

Java内存模型之可见性问题

慕课网学习笔记Java共享变量的可见性和原子性

JVM学习--内存模型可见性指令重排序