• 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();//注意是否可行
        }
    }
  • 相关阅读:
    循环队列和链队列的实现
    【lightoj-1026】Critical Links(桥)
    顺序栈和链栈的实现
    【51nod-1605】棋盘问题
    【51nod-1596】搬货物
    【海明码】(容易看懂)
    【lightoj-1094】树的直径(DFS)
    【lightoj-1046】Rider(BFS)
    【第13届景驰-埃森哲杯广东工业大学ACM程序设计大赛-F】等式(因子个数)
    浅谈Vue个性化dashBoard 布局
  • 原文地址:https://www.cnblogs.com/caiyishuai/p/9783779.html
Copyright © 2020-2023  润新知