发布于2021-06-12 15:42 阅读(266) 评论(0) 点赞(29) 收藏(3)
UML类图
建模语言或标准建模语言
类的属性、操作中的可见性使用+、#、-分别表示public、protected、private
属性封装
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
*/
师承上官可编程 —— 陈立臣
原文链接:https://blog.csdn.net/m0_51247005/article/details/117674783
作者:狗蛋来了
链接:http://www.javaheidong.com/blog/article/222587/19f8d2b7510315807513/
来源:java黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 java黑洞网 All Rights Reserved 版权所有,并保留所有权利。京ICP备18063182号-2
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!