Java學習——包及可見性
阿新 • • 發佈:2018-10-13
不可見 package 可見性 out this port string 修飾符 main
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學習——包及可見性