复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77//为什么要有封装? class Person { String name; // 声明姓名属性 int age; // 声明姓名属性 public void showInfo() { //获取信息的方法 System.out.println("姓名:" + name + ",年龄:" + age); } } public class Test { public static void main(String args[]){ Person per = new Person() ; //声明并实例化对象 per.name = "张三"; // 为name属性赋值 per.age = -30; // 为age属性赋值 per.showInfo(); // 调用类中的方法 } } //为属性封装:private 属性类型 属性名称 ; //为方法封装:private 方法返回值 方法名称(参数列表){} //Setter及Getter方法 class Person { private String name; // 声明姓名属性 private int age; // 声明年龄属性 public String getName(){ return name; } public void setName(String name){ this.name=name; } public int getAge(){ return age; } public void setAge(int age){ this.age=age; } public void showInfo() { // 取得信息的方法 System.out.println("姓名:" + getName() + ",年龄:" + getAge()); } } public class Testc{ public static void main(String args[]) { Person per = new Person(); per.setName("张三"); per.setAge(9); per.showInfo(); } } //声明一个构造方法 class Student { public Student(){ // 声明构造方法 System.out.println("一个新的Student对象产生。") ; } } public class Testc { public static void main(String args[]) { System.out.println("声明对象:Student stu = null;") ; Student stu = null ; // 声明对象时不调用构造 System.out.println("实例化对象:stu = new Student() ;") ; stu = new Student(); // 实例化对象时调用构造 } } //默认构造方法 //每个类中肯定都会有一个构造方法 //如果一个类中没有声明构造方法,则会自动生成一个无参的什么都不做的构造方法 class Person { public Person(){ } }
最后
以上就是怕孤独大象最近收集整理的关于类的封装以及构造方法的全部内容,更多相关类内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复