封装是一种 信息隐藏技术 ,在java中通过关键字private,protected和public实现封装。封装把对象的所有组成部分组合在一起,封装定义程序如何引用对象的数据,封装实际上使用方法将类的数据隐藏起来,控制用户对类的修改和访问数据的程度。适当的封装可以让程式码更容易理解和维护,也加强了程式码的安全性。
构造方法:
1.它是用来创建对象的
2.类默认创建无参的构造方法如果自定了任意一个构造方法那么系统就不会再给你创建默认的构造方法
3.无参的构造方法是用来实例化对象的有参的构造方法不仅实例化对象同时给类的属性方法赋值
复制代码
1
2
3
4
5
6
7
8
9
10
11public Books() { } public Books(int bookId, String bookName, String bookAuthor, int bookNum, double bookPrice, String introduce) { this.bookId = bookId; this.bookName = bookName; this.bookAuthor = bookAuthor; this.bookNum = bookNum; this.bookPrice = bookPrice; this.introduce = introduce; }
toString 给对应变量赋值,没有toString打印输出内存地址
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14 @Override public String toString() { return "Books{" + "bookId=" + bookId + ", bookName='" + bookName + ''' + ", bookAuthor='" + bookAuthor + ''' + ", bookNum=" + bookNum + ", bookPrice=" + bookPrice + ", introduce=" + introduce + '}'; }
针对属性设置getter和setter方法完成对属性的获取和赋值
复制代码
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
66package com.company.bean2; public class Books { private int bookId; private String bookName; private String bookAuthor; private int bookNum; private double bookPrice; private String introduce; public int getBookId() { return bookId; } public void setBookId(int bookId) { this.bookId = bookId; } public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } public String getBookAuthor() { return bookAuthor; } public void setBookAuthor(String bookAuthor) { this.bookAuthor = bookAuthor; } public int getBookNum() { return bookNum; } public void setBookNum(int bookNum) { if (bookNum >= 0 && bookNum <= 100) { this.bookNum = bookNum; } } public double getBookPrice() { return bookPrice; } public void setBookPrice(double bookPrice) { this.bookPrice = bookPrice; } public String getIntroduce() { return introduce; } public void setIntroduce(String introduce) { this.introduce = introduce; } }
提高代码安全性
复制代码
1
2
3
4
5
6
7
8public class Books { private int bookId; private String bookName; private String bookAuthor; private int bookNum; private double bookPrice; private String introduce; }
最后
以上就是缓慢春天最近收集整理的关于封装的概念的全部内容,更多相关封装内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复