zoukankan      html  css  js  c++  java
  • 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();//注意是否可行
        }
    }
  • 相关阅读:
    C#实现汉字转换为拼音缩写的代码
    C# 使用xsd文件验证XML 格式是否正确
    C#用天气预报的WebServices
    c# socket通信较完善方案
    C#操作MySQL数据库-----HelloWorld
    c# 自己制作一个简单的项目倒计时器
    C# 制作外挂常用的API
    C#中如何计算时间差?
    C# 图片保存到数据库和从数据库读取图片并显示
    c#加密 可逆与不可逆MD5 加密
  • 原文地址:https://www.cnblogs.com/caiyishuai/p/9783779.html
Copyright © 2011-2022 走看看