详解Java中的访问修饰符?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
UML类图
建模语言或标准建模语言
类的属性、操作中的可见性使用+、#、-分别表示public、protected、private
作用:信息隐藏
防止用户意外修改数据,使模块易于维护和使用有哪些修饰符呢?
private:只有该类可以访问
protected:该类及其子类的成员可以访问,同一个包中的类也可以访问
public:该类或非该类可以访问
默认:同一个包中的类可以访问
可以作用于类,成员,方法
同一个类
就是同一个类里面的,类相当于结构体
同一个包
圈中的就是包
属性封装
class Student{//class 相当于c语言的struct
int age;
String name;
double score;
private int sex; //不同类,无法访问这个成员
public void cs(int a){
sex = a;
}
void introduce(){
System.out.println("sex="+sex+",age="+ age +",name=" + name + ",score=" + score);
}
void testFunc(){
System.out.println("testFunc");
}
}
public class Test {
public static void main(String[] args) {
Student stu1 = new Student();
//stu1.sex = 1; 因为类里面使用了private,不同类就无法访问
stu1.cs(0); //可以使用方法,间接修改成员
stu1.age = 22;
stu1.name = "xiaowei";
stu1.score = 100;
stu1.introduce();
stu1.testFunc();
}
}
/*
sex=0,age=22,name=xiaowei,score=100.0
testFunc
*/
方法封装
class Student{//class 相当于c语言的struct
private int age;
String name;
double score;
private int sex;
private void myage(int myage){ //不可见的方法,可以在别的方法中使用达到更改属性的目的
age = myage;
}
public void setage(int realage){ //更改age
age = realage;
}
public int getage(){ //输出age,方法里偷偷使用myage,输出永远是18
myage(18);
return age;
}
void cs(int a){
sex = a;
}
void introduce(){
System.out.println("sex="+sex+",age="+ age +",name=" + name + ",score=" + score);
}
void testFunc(){
System.out.println("testFunc");
}
}
public class Test {
public static void main(String[] args) {
Student stu1 = new Student();
//stu1.sex = 1;
stu1.cs(0);
//stu1.age = 22;
stu1.setage(36); //更改年龄36
stu1.name = "xiaowei";
stu1.score = 100;
stu1.introduce();
stu1.testFunc();
System.out.println("age="+stu1.getage()); //输出年龄是18,方法中偷偷调用了不可见的方法myage
}
}
/*
sex=0,age=36,name=xiaowei,score=100.0
testFunc
age=18
*/
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。