我是靠谱客的博主 缓慢春天,最近开发中收集的这篇文章主要介绍封装的概念,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

封装是一种 信息隐藏技术 ,在java中通过关键字private,protected和public实现封装。封装把对象的所有组成部分组合在一起,封装定义程序如何引用对象的数据,封装实际上使用方法将类的数据隐藏起来,控制用户对类的修改和访问数据的程度。适当的封装可以让程式码更容易理解和维护,也加强了程式码的安全性。

构造方法:

1.它是用来创建对象的

2.类默认创建无参的构造方法如果自定了任意一个构造方法那么系统就不会再给你创建默认的构造方法

3.无参的构造方法是用来实例化对象的有参的构造方法不仅实例化对象同时给类的属性方法赋值

  public 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打印输出内存地址

​
  @Override
    public String toString() {
        return "Books{" +
                "bookId=" + bookId +
                ", bookName='" + bookName + ''' +
                ", bookAuthor='" + bookAuthor + ''' +
                ", bookNum=" + bookNum +
                ", bookPrice=" + bookPrice +
                ", introduce=" + introduce +
                '}';
    }
 
​

针对属性设置getter和setter方法完成对属性的获取和赋值

package 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;
    }
 
  
}

提高代码安全性

public class Books {
    private int bookId;
    private String bookName;
    private String bookAuthor;
    private int bookNum;
    private double bookPrice;
    private String introduce;
}

最后

以上就是缓慢春天为你收集整理的封装的概念的全部内容,希望文章能够帮你解决封装的概念所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(36)

评论列表共有 0 条评论

立即
投稿
返回
顶部