• JAVA基础(八)


    面向对象特征之一:封装和隐藏

    我们程序设计追求“高内聚,低耦合”

            高内聚 :类的内部数据操作细节自己完成,不允许外部干涉;

            低耦合 :仅对外暴露少量的方法用于使用。

    隐藏对象内部的复杂性,只对外公开简单的接口。便于外界调用,从而提高系统的可扩展性、可维护性。通俗的说,把该隐藏的隐藏起来,该暴露 的暴露出来。这就是封装性的设计思想。

    信息的封装和隐藏

    Java中通过将数据声明为私有的(private),再提供公共的(public) 方法:getXxx()和setXxx()实现对该属性的操作,以实现下述目的:

            隐藏一个类中不需要对外提供的实现细节;

            使用者只能通过事先定制好的方法来访问数据,可以方便地加入控制逻辑, 限制对属性的              不合理操作;

            便于修改,增强代码的可维护性;

    1. package com.xxx.java;
    2. public class AnimalTest {
    3. public static void main(String[] args) {
    4. Animal a = new Animal();
    5. a.name = "花花";
    6. a.age = 1;
    7. //a.legs = 1; //The field Animal.legs is not visible
    8. a.setLegs(6);
    9. a.show();
    10. a.eat();
    11. }
    12. }
    13. class Animal {
    14. String name;
    15. int age;
    16. private int legs; //防止用户跳出限制
    17. //对属性的设置
    18. public void setLegs(int l) { //为了禁止用户输入负数和奇数
    19. if (l >= 0 && l % 2 == 0) {
    20. legs = l;
    21. } else {
    22. legs = 0;
    23. //抛出异常(后续完善)
    24. }
    25. }
    26. //对属性的获取
    27. public int getLegs() {
    28. return legs;
    29. }
    30. public void eat() {
    31. System.out.println("动物进食");
    32. }
    33. public void show() {
    34. System.out.println("name = " + name + ",age = " + age + ",legs = " + legs);
    35. }
    36. }

    四种访问权限修饰符

    Java权限修饰符public、protected、(缺省)、private置于类的成员定义前用来限定对象对该类成员的访问权限。

     对于class的权限修饰只可以用public和default(缺省)。

            public类可以在任意地方被访问。

            default类只可以被同一个包内部的类访问。

            4种权限都可以用来修饰类的内部结构:属性、方法、构造器、内部类

                    修饰类的话:只能使用:缺省、public

    1. package com.xxx.java;
    2. public class Order {
    3. private int orderPrivate;
    4. int orderDefault;
    5. public int orderPublic;
    6. private void methodPrivate() {
    7. orderPrivate = 1;
    8. orderDefault = 2;
    9. orderPublic = 3;
    10. }
    11. void methodDefault() {
    12. orderPrivate = 1;
    13. orderDefault = 2;
    14. orderPublic = 3;
    15. }
    16. public void methodPublic() {
    17. orderPrivate = 1;
    18. orderDefault = 2;
    19. orderPublic = 3;
    20. }
    21. }
    1. package com.xxx.java;
    2. public class OrderTest {
    3. public static void main(String[] args) {
    4. Order order = new Order();
    5. order.orderDefault = 1;
    6. order.orderPublic = 2;
    7. //私有结构无法调用
    8. //order.orderPrivate = 3;
    9. order.methodDefault();
    10. order.methodPublic();
    11. //私有结构无法调用
    12. //order.methodPrivate();
    13. }
    14. }
    1. package com.xxx.java1;
    2. import com.xxx.java.Order;
    3. public class OrderTest {
    4. public static void main(String[] args) {
    5. Order order = new Order();
    6. //缺省结构出了包后无法调用
    7. //order.orderDefault = 1;
    8. order.orderPublic = 2;
    9. //私有结构出了类后无法调用
    10. //order.orderPrivate = 3;
    11. //缺省结构出了包后无法调用
    12. //order.methodDefault();
    13. order.methodPublic();
    14. //私有结构出了类后无法调用
    15. //order.methodPrivate();
    16. }
    17. }

    创建程序,在其中定义两个类:Person和PersonTest类。

    定义如下: 用setAge()设置人的合法年龄(0~130),用getAge()返回人的年龄。

    在 PersonTest 类 中实例化 Person 类的对象 b , 调 用 setAge() 和 getAge()方法,体会Java的封装性。

    1. package com.xxx.exer;
    2. public class Person {
    3. private int age;
    4. public void setAge(int i) {
    5. if(i >= 0 && i <= 130) {
    6. age = i;
    7. }else {
    8. System.out.println("age的范围为0-130,请重新设置");
    9. }
    10. }
    11. public int getAge() {
    12. return age;
    13. }
    14. }
    1. package com.xxx.exer;
    2. public class PersonTest {
    3. public static void main(String[] args) {
    4. Person p1 = new Person();
    5. p1.setAge(12);
    6. System.out.println(p1.getAge());
    7. }
    8. }

     

    类的成员之三:构造器(构造方法)

    构造器的特征

            它具有与类相同的名称

            它不声明返回值类型。(与声明为void不同)

            不能被static、final、synchronized、abstract、native修饰,不能有 return语句返回值

    说明:

            如果没有显式的定义类的构造器,则默认提供一个空参的构造器

            一个类中的多个构造器,彼此构成重载

            一旦显示的定义了类的构造器后,系统就不在提供默认的空参构造器

    构造器的作用:

            创建对象;

            给对象进行初始化

    语法格式:

    1. 修饰符 类名 (参数列表) {
    2. 初始化语句;
    3. }
    1. package com.xxx.java1;
    2. public class PersonTest {
    3. public static void main(String[] args) {
    4. //创建类的对象:new + 构造器
    5. Person p = new Person();
    6. Person p1 = new Person("Tom");
    7. p.eat();
    8. }
    9. }
    10. class Person {
    11. //属性
    12. String name;
    13. int age;
    14. //构造器
    15. public Person() {
    16. System.out.println("Person!");
    17. }
    18. public Person(String n) {
    19. name = n;
    20. }
    21. public Person(String n, int a) {
    22. name = n;
    23. age = a;
    24. }
    25. //方法
    26. public void eat() {
    27. System.out.println("人吃饭");
    28. }
    29. public void study() {
    30. System.out.println("人学习");
    31. }
    32. }

    1. 在练习1定义的Person类中添加构造器,利用构造器设置所有人的age属 性初始值都为18。

    2. 修改上题中类和构造器,增加name属性,使得每次创建Person对象的同 时初始化对象的age属性值和name属性值

    1. package com.xxx.exer;
    2. public class Person {
    3. private int age;
    4. private String name;
    5. public Person() {
    6. age = 18;
    7. }
    8. public Person(int a,String s) {
    9. age = a;
    10. name = s;
    11. }
    12. public void setAge(int i) {
    13. if(i >= 0 && i <= 130) {
    14. age = i;
    15. }else {
    16. System.out.println("age的范围为0-130,请重新设置");
    17. }
    18. }
    19. public int getAge() {
    20. return age;
    21. }
    22. public void setName(String s) {
    23. name = s;
    24. }
    25. public String getName() {
    26. return name;
    27. }
    28. }
    1. package com.xxx.exer;
    2. public class PersonTest {
    3. public static void main(String[] args) {
    4. Person p1 = new Person();
    5. // p1.setAge(12);
    6. System.out.println(p1.getAge());
    7. Person p2 = new Person(5,"Tom");
    8. System.out.println(p2.getAge());
    9. System.out.println(p2.getName());
    10. }
    11. }

    3.编写两个类,TriAngle和TriAngleTest,其中TriAngle类中声明私有的底边长base和高height,同时声明公共方法访问私有变量。此外,提供类 必要的构造器。另一个类中使用这些公共方法,计算三角形的面积

    1. package com.xxx.exer;
    2. public class TriAngle {
    3. private double base;
    4. private double height;
    5. public TriAngle() {
    6. }
    7. public TriAngle(double b,double h) {
    8. base = b;
    9. height = h;
    10. }
    11. public void setBase(double b) {
    12. base = b;
    13. }
    14. public double getBase() {
    15. return base;
    16. }
    17. public void setHeight(double h) {
    18. height = h;
    19. }
    20. public double getHeight() {
    21. return height;
    22. }
    23. public double getArea() {
    24. return (base * height) / 2;
    25. }
    26. }

    测试

    1. package com.xxx.exer;
    2. public class TriAngleTest {
    3. public static void main(String[] args) {
    4. TriAngle t1 = new TriAngle(10,20);
    5. System.out.println(t1.getBase());
    6. System.out.println(t1.getHeight());
    7. System.out.println(t1.getArea());
    8. }
    9. }

    总结:属性赋值过程

    截止到目前,我们讲到了很多位置都可以对类的属性赋值。现总结这几个位 置,并指明赋值的先后顺序。

    赋值的位置:

            ① 默认初始化

            ② 显式初始化

           ③ 构造器中初始化 

            ④ 通过“对象.属性“或“对象.方法”的方式赋值

    赋值的先后顺序:

            ① - ② - ③ - ④

    1. package com.xxx.java1;
    2. public class UserTest {
    3. public static void main(String[] args) {
    4. //证明显式比默认初始化后赋值
    5. User u = new User();
    6. System.out.println(u.age);
    7. //证明构造器比显式后赋值
    8. User u1 = new User(5);
    9. System.out.println(u1.age);
    10. //证明通过“对象.属性“或“对象.方法”的方式比构造器后赋值
    11. u1.age = 8;
    12. System.out.println(u1.age);
    13. }
    14. }
    15. class User{
    16. String name;
    17. int age = 1;
    18. public User() {
    19. }
    20. public User(int a) {
    21. age = a;
    22. }
    23. }

    JavaBean

    JavaBean是一种Java语言写成的可重用组件。

    所谓javaBean,是指符合如下标准的Java类:

            类是公共的

            有一个无参的公共的构造器

            有属性,且有对应的get、set方法

    1. package com.xxx.java1;
    2. public class JavaBean {
    3. private int age;
    4. public JavaBean() {
    5. }
    6. public void setAge(int a) {
    7. age = a;
    8. }
    9. public int getAge() {
    10. return age;
    11. }
    12. }

    用户可以使用JavaBean将功能、处理、值、数据库访问和其他任何可以用Java代码创造的对象进行打包并且其他的开发者可以通过内部的JSP 页面、Servlet、其他JavaBean、applet程序或者应用来使用这些对象。用户可以认为JavaBean提供了一种随时随地的复制和粘贴的功能,而不用关心任何改变。

    UML类图

    关键字—this

    在Java中,this关键字比较难理解,它的作用和其词义很接近。

            它在方法内部使用,即这个方法所属对象的引用;

            它在构造器内部使用,表示该构造器正在初始化的对象。

    this可以调用类的属性、方法和构造器

    什么时候使用this关键字呢?

            当在方法内需要用到调用该方法的对象时,就用this。

    this调用构造器

    注意:

            可以在类的构造器中使用"this(形参列表)"的方式,调用本类中重载的其他的构造器!

            明确:构造器中不能通过"this(形参列表)"的方式调用自身构造器

            如果一个类中声明了n个构造器,则最多有 n - 1个构造器中使用了 "this(形参列表)"

            "this(形参列表)"必须声明在类的构造器的首行!

            在类的一个构造器中,最多只能声明一个"this(形参列表)"

    可以在工具栏的source或快捷键alt+shift+s快速生成代码

    如:getter和setter,构造器等

    练习

    添加必要的构造器,综合应用构造器的重载,this关键字

    1. package com.xxx.exer;
    2. public class Boy {
    3. private String name;
    4. private int age;
    5. public Boy() {
    6. super();
    7. }
    8. public Boy(String name, int age) {
    9. this.name = name;
    10. this.age = age;
    11. }
    12. public String getName() {
    13. return name;
    14. }
    15. public void setName(String name) {
    16. this.name = name;
    17. }
    18. public int getAge() {
    19. return age;
    20. }
    21. public void setAge(int age) {
    22. this.age = age;
    23. }
    24. public void marry(Girl girl) {
    25. System.out.println("我想娶" + girl.getName());
    26. }
    27. public void shout() {
    28. if(age >= 22) {
    29. System.out.println("你可以去结婚了");
    30. }else {
    31. System.out.println("先谈恋爱吧");
    32. }
    33. }
    34. }

     

    1. package com.xxx.exer;
    2. public class Girl {
    3. private String name;
    4. private int age;
    5. public Girl(String name, int age) {
    6. this.name = name;
    7. this.age = age;
    8. }
    9. public String getName() {
    10. return name;
    11. }
    12. public void setName(String name) {
    13. this.name = name;
    14. }
    15. public int getAge() {
    16. return age;
    17. }
    18. public void setAge(int age) {
    19. this.age = age;
    20. }
    21. public void marry(Boy boy) {
    22. System.out.println("我想嫁给" + boy.getName());
    23. boy.marry(this);
    24. }
    25. public int compare(Girl girl) {
    26. if(this.age > girl.age) {
    27. return 1;
    28. }else if(this.age > girl.age) {
    29. return -1;
    30. }else {
    31. return 0;
    32. }
    33. }
    34. }

    测试

    1. package com.xxx.exer;
    2. public class BoyGirlTest {
    3. public static void main(String[] args) {
    4. Boy boy = new Boy("罗密欧",21);
    5. boy.shout();
    6. Girl girl = new Girl("朱丽叶",18);
    7. girl.marry(boy);
    8. Girl girl1 = new Girl("祝英台",19);
    9. System.out.println(girl1.compare(girl));
    10. }
    11. }

     

    1.写一个名为 Account 的类模拟账户。该类的属性和方法如下图所示。该类包括的属性: 账号 id,余额 balance,年利率 annualInterestRate;包含的方法:访问器方法(getter 和 setter 方法),取款方法 withdraw(),存款方法 deposit()。

     提示:在提款方法 withdraw 中,需要判断用户余额是否能够满足提款数额的要求,如果不                        能,应给出提示。

    2. 创建 Customer 类。

            a. 声明三个私有对象属性:firstName、lastName 和 account。

            b. 声明一个公有构造器,这个构造器带有两个代表对象属性的参数(f 和 l)

            c. 声明两个公有存取器来访问该对象属性,方法 getFirstName 和 getLastName 返回相应                  的属性。

            d. 声明 setAccount 方法来对 account 属性赋值。

            e. 声明 getAccount 方法以获取 account 属性。

    3.写一个测试程序。

            (1) 创建一个 Customer ,名字叫 Jane Smith, 他有一个账号为 1000,余额为 2000 元,                      年利率为 1.23% 的账户。

            (2) 对 Jane Smith 操作。

                    存入 100 元,再取出 960 元。再取出 2000 元。

                    打印出 Jane Smith 的基本信息

    1. package com.xxx.exer;
    2. public class Account {
    3. private int id;
    4. private double balance;
    5. private double annualInterestRate;
    6. public Account(int id, double balance, double annualInterestRate) {
    7. super();
    8. this.id = id;
    9. this.balance = balance;
    10. this.annualInterestRate = annualInterestRate;
    11. }
    12. public int getId() {
    13. return id;
    14. }
    15. public void setId(int id) {
    16. this.id = id;
    17. }
    18. public double getBalance() {
    19. return balance;
    20. }
    21. public void setBalance(double balance) {
    22. this.balance = balance;
    23. }
    24. public double getAnnualInterestRate() {
    25. return annualInterestRate;
    26. }
    27. public void setAnnualInterestRate(double annualInterestRate) {
    28. this.annualInterestRate = annualInterestRate;
    29. }
    30. public void withdraw(double amount) {
    31. if(balance >= amount) {
    32. balance -= amount;
    33. System.out.println("成功取出:" + amount + ",当前账户剩余" + balance);
    34. }else {
    35. System.out.println("余额不足,取款失败");
    36. }
    37. }
    38. public void deposit (double amount) {
    39. if(amount > 0) {
    40. balance += amount;
    41. System.out.println("成功存入 :" + amount + ",当前账户剩余" + balance);
    42. }
    43. }
    44. }
    1. package com.xxx.exer;
    2. public class Customer {
    3. private String firstName;
    4. private String lastName;
    5. private Account account;
    6. public Customer(String f, String l) {
    7. this.firstName = f;
    8. this.lastName = l;
    9. }
    10. public String getFirstName() {
    11. return firstName;
    12. }
    13. public String getLastName() {
    14. return lastName;
    15. }
    16. public Account getAccount() {
    17. return account;
    18. }
    19. public void setAccount(Account account) {
    20. this.account = account;
    21. }
    22. }

    测试

    1. package com.xxx.exer;
    2. public class Test {
    3. public static void main(String[] args) {
    4. Customer c1 = new Customer("Jane", "Smith");
    5. Account a = new Account(1000,2000,1.23);
    6. c1.setAccount(a);
    7. c1.getAccount().deposit(100);
    8. c1.getAccount().withdraw(960);
    9. c1.getAccount().withdraw(2000);
    10. }
    11. }

    1.按照如下的 UML 类图,创建相应的类,提供必要的结构

     ​​​​​​在提款方法 withdraw()中,需要判断用户余额是否能够满足提款数额的要求,如果不能, 应给出提示。deposit()方法表示存款。

     2. 按照如下的 UML 类图,创建相应的类,提供必要的结构

    3. 按照如下的 UML 类图,创建相应的类,提供必要的结构

            addCustomer 方法必须依照参数(姓,名)构造一个新的 Customer 对象,然后把它放到              customer 数组中。还必须把 numberOfCustomer 属性的值加 1

            getNumOfCustomers 方法返回 numberofCustomers 属性值。

            getCustomer 方法返回与给出的 index 参数相关的客户。

            创建 BankTest 类,进行测试。

    1. package com.xxx.erer2;
    2. public class Account {
    3. private double balance;
    4. public Account(double init_balance) {
    5. this.balance = init_balance;
    6. }
    7. public double getBalance() {
    8. return balance;
    9. }
    10. //存款
    11. public void deposit (double amt) {
    12. if(amt > 0) {
    13. balance += amt;
    14. System.out.println("成功存入 :" + amt);
    15. }
    16. }
    17. //取款
    18. public void withdraw(double amt) {
    19. if(balance >= amt) {
    20. balance -= amt;
    21. System.out.println("成功取出:" + amt);
    22. }else {
    23. System.out.println("余额不足,取款失败");
    24. }
    25. }
    26. }
    1. package com.xxx.erer2;
    2. public class Customer {
    3. private String firstName;
    4. private String lastName;
    5. private Account account;
    6. public Customer(String f, String l) {
    7. this.firstName = f;
    8. this.lastName = l;
    9. }
    10. public String getFirstName() {
    11. return firstName;
    12. }
    13. public String getLastName() {
    14. return lastName;
    15. }
    16. public Account getAccount() {
    17. return account;
    18. }
    19. public void setAccount(Account acct) {
    20. this.account = acct;
    21. }
    22. }
    1. package com.xxx.erer2;
    2. public class Bank {
    3. private int numberOfCustomer;
    4. private Customer[] customers;
    5. public Bank() {
    6. customers = new Customer[10];
    7. }
    8. public int getNumberOfCustomer() {
    9. return numberOfCustomer;
    10. }
    11. public void addCustomer(String f,String l) {
    12. Customer c = new Customer(f, l);
    13. customers[numberOfCustomer] = c;
    14. numberOfCustomer++;
    15. }
    16. public Customer getCustomer(int index) {
    17. if (index > numberOfCustomer || index < 0) {
    18. return null;
    19. } else {
    20. return customers[index];
    21. }
    22. }
    23. }

    测试

    1. package com.xxx.erer2;
    2. public class BankTest {
    3. public static void main(String[] args) {
    4. Bank bank = new Bank();
    5. bank.addCustomer("Jane", "Smith");
    6. bank.getCustomer(0).setAccount(new Account(2000));
    7. bank.getCustomer(0).getAccount().withdraw(500);
    8. System.out.println(
    9. "客户:" + bank.getCustomer(0).getFirstName() + " 余额为:" + bank.getCustomer(0).getAccount().getBalance());
    10. bank.addCustomer("Mary", "Brown");
    11. System.out.println("银行客户的个数为:" + bank.getNumberOfCustomer());
    12. }
    13. }

    关键字:package、 import的使用

    package的使用

    package语句作为Java源文件的第一条语句,指明该文件中定义的类所在的包。(若缺省该语句,则指定为无名包)。它的格式为:

            举例:pack1\pack2\PackageTest.java

    1. package pack1.pack2; //指定类PackageTest属于包pack1.pack2
    2. public class PackageTest{
    3. public void display(){
    4. System.out.println("in method display()");
    5. }
    6. }

    包对应于文件系统的目录,package语句中,用 “.” 来指明包(目录)的层次;

    包通常用小写单词标识。通常使用所在公司域名的倒置:com.atguigu.xxx

    包的作用:

            包帮助管理大型软件系统:将功能相近的类划分到同一个包中。比如:MVC的设计模式

            包可以包含类和子包,划分项目层次,便于管理

            解决类命名冲突的问题

            控制访问权限

    MVC设计模式

    MVC是常用的设计模式之一,将整个程序分为三个层次:视图模型层,控制器层,与 数据模型层。这种将程序输入输出、数据处理,以及数据的展示分离开来的设计模式 使程序结构变的灵活而且清晰,同时也描述了程序各个对象间的通信方式,降低了程 序的耦合性。

    模型层 model 主要处理数据

            数据对象封装 model.bean/domain

            数据库操作类 model.dao

            数据库 model.db

    视图层 view 显示数据

            相关工具类 view.utils

            自定义view view.ui

    控制层 controller 处理业务逻辑

            应用界面相关 controller.activity

            存放fragment controller.fragment

            显示列表的适配器 controller.adapter

            服务相关的 controller.service

            抽取的基类 controller.base

    JDK中主要的包介绍

    java.lang----包含一些Java语言的核心类,如String、Math、Integer、 System和 Thread,提供常                     用功能

    java.net----包含执行与网络相关的操作的类和接口。

    java.io ----包含能提供多种输入/输出功能的类。

    java.util----包含一些实用工具类,如定义系统特性、接口的集合框架类、使用与日 期日历相关的                     函数。

    java.text----包含了一些java格式化相关的类

    java.sql----包含了java进行JDBC数据库编程的相关类/接口

    java.awt----包含了构成抽象窗口工具集(abstract window toolkits)的多个类,这 些类被用来构建                    和管理应用程序的图形用户界面(GUI)。 B/S C/S

    关键字—import

    为使用定义在不同包中的Java类,需用import语句来引入指定包层次下所需要的类 或全部类(.*)。

            import语句告诉编译器到哪里去寻找类。

    语法格式:

    import 包名. 类名;
    

    注意:

            1. 在源文件中使用import显式的导入指定包下的类或接口

            2. 声明在包的声明和类的声明之间。

            3. 如果需要导入多个类或接口,那么就并列显式多个import语句即可

            4. 举例:可以使用java.util.*的方式,一次性导入util包下所有的类或接口。

            5. 如果导入的类或接口是java.lang包下的,或者是当前包下的,则可以省略此import语句。

            6. 如果在代码中使用不同包下的同名的类。那么就需要使用类的全类名的方式指明调用的是              哪个类。

    1. //全类名
    2. com.xxx.erer3.Account

            7. 如果已经导入java.a包下的类。那么如果需要使用a包的子包下的类的话,仍然需要导入。

            8. import static组合的使用:调用指定类或接口下的静态的属性或方法  

  • 相关阅读:
    基本语法(三)
    Java(六)——常用类System
    基于scRNA-seq的GRN分析三阴性乳腺癌的肿瘤异质性
    编程软件大全(下载+安装+破解)
    TransReID | 首次将transformer应用于行人重识别
    上周热点回顾(7.31-8.6)
    大数据常见面试题
    JSP中如何借助response对象实现页面跳转呢?
    CIKM 2020 | FANG:利用社会语境及其图表示进行假新闻检测
    专业技能篇---计算机网络
  • 原文地址:https://blog.csdn.net/m0_56413004/article/details/126063027