Han Shunping learned Java in 30 days with zero foundation [Chapter 7 Object-Oriented Programming (Intermediate)]

P273~P359

Bag

  1. Differentiate between classes with the same name
  2. When there are many classes, the classes can be well managed
  3. Control Access Scope

In fact, it is to create different folders to save the class files

grammar

package 包名;

Package Naming Rules

Can only contain numbers, letters, underscores, dots, cannot start with numbers, cannot contain keywords or reserved words

Naming conventions

Generally com.company name.project name.business module name

commonly used package

  • java.lang.*, basic package, imported by default, no need to import again
  • java.util.*, util package, toolkit provided by the system, tool class, using Scanner
  • java.net .*, webpackage, web development
  • java.awt.*, do java interface development, GUI

new package

Right click on the src folder → package input com.xiaoming

How to import the package, Import01.java/

package com.pkg;
import java.util.Arrays;
import java.util.Scanner;

public class Import01 {
    public static void main(String[] args) {
        //使用系统提供的Arrays 完成数组排序
        int[] arr = {-1,20,2,13,3};
        //对其排序
        //传统方法是,自己编写排序
        //系统提供相应的类,可以方便完成 Arrays
        Arrays.sort(arr);
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
}

Notes and Details, PkgDetail.java

The function of package is to declare the package where the current class is located. It needs to be placed at the top of the class. There is at most one sentence of package in a class.

importInstructions, the position is placed packagebelow, before the class definition, there can be multiple sentences and there is no order requirement.

package com.pkg;

import java.util.Arrays;
import java.util.Scanner;

public class PkgDetail {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int[] arr = {-1, 2, 2};
        Arrays.sort(arr);
    }
}

access modifier

Used to control access to methods and properties

  1. Public: public, open to the public
  2. Protected: protected, exposed to subclasses and classes in the same package
  3. Default: no modifiers, exposed to classes in the same package
  4. Private: private, only the class itself can access
access level access control modifier similar Same bag Subclass different packages<br>
public public
protected protected x
default none x x
private private x x x

Access modifier details

  1. Modifiers can be used to modify properties, member methods, and classes in a class
  2. Only the default and public can modify the class, and follow the characteristics of the above access rights
  3. Because there is no learning inheritance, about the access rights in subclasses, read it after you finish talking about subclasses
  4. Access rules for member methods are exactly the same as for properties

encapsulation

Encapsulate the abstracted data (attributes) and operations on the data (methods), the data is protected internally, and other parts of the program can only operate on the data through authorized operations

benefit

  1. hide implementation details
  2. Data can be verified to ensure safety and reasonableness

Implementation steps

  1. Make properties private
  2. Provide a public set method for judging and assigning values ​​to attributes
  3. Provide a public get method for getting the value of the property

Quick Start, com.encap.Encapsulation01.java

You can’t just check people’s age, salary and other privacy, and do a reasonable verification of the set age. If the age is reasonable, set it, otherwise it will be the default

Age must be between 1-120, age and salary cannot be viewed directly, name length is between 2-6 characters

package com.encap;

public class Encapsulation01 {
    public static void main(String[] args) {
        Person person = new Person();
        person.name = "Jack";
        person.setAge(10);
        person.setSalay(100.5);
        System.out.println(person.info());
        Person person1 = new Person("smith", 200, 2000);
        System.out.println(person1.info());
    }
}
//    不能随便查看人的年龄、工资等隐私,并对设置的年龄进行合理的验证,
//    年龄合理就设置,否则就默认
//    年龄必须在1-120之间,年龄,工资不能直接查看,name长度在2-6字符之间

class Person {
    public String name;
    private int age;//年龄私有化
    private double salay;

    //构造器
    public Person() {
    }

    //三个属性的构造器
    //可以将set方法写在构造器中,这样仍然可以验证数据
    public Person(String name, int age, double salay) {
        setName(name);
        setAge(age);
        setSalay(salay);
    }


    //set,get方法生成快捷键

    public String getName() {
        return name;
    }

    public void setName(String name) {
        if (name.length() >= 2 && name.length() <= 6) {
            this.name = name;
        } else {
            System.out.println("名字长度不对");
            this.name = "无名";
        }
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        //    年龄必须在1-120之间,年龄,工资不能直接查看,name长度在2-6字符之间
        if (age >= 1 && age <= 120) {
            this.age = age;
        } else {
            System.out.println("设置年龄错误,年龄需要在1-120");
            this.age = 18;
        }
    }

    public double getSalay() {
        return salay;
    }

    public void setSalay(double salay) {
        this.salay = salay;
    }

    public String info() {
        return "信息为" + name + " " + getAge() + " " + getSalay();
    }
}

Class Exercises, com.encap.AccountTest.java and Account.java

Create a program, define two classes in it: Account and AccountTest class, experience java encapsulation

  1. The Account class requires attributes: name (length 2, 3, 4), balance (>20), password (6 digits), if not satisfied, give a prompt message and give a default value
  2. Assign values ​​to the properties of Account through the setXxx method
  3. Test in AccountTest
package com.encap;

public class Account {
    private String name;
    private int account;
    private String code;

    public Account(String name, int account, String code) {
        setAccount(account);
        setCode(code);
        setName(name);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        if (name.length() >= 2 && name.length() <= 4) {
            this.name = name;
        } else {
            System.out.println("name长度不对");
            this.name = "无名";
        }
    }

    public int getAccount() {
        return account;
    }

    public void setAccount(int account) {
        if (account > 20) {
            this.account = account;
        } else {
            System.out.println("account<20");
            this.account = 20;
        }
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        if (code.length() == 6) {
            this.code = code;
        } else {
            System.out.println("密码长度不为6");
            this.code = "111111";
        }
    }

    public String info() {
        return "信息为" + getName() + " " + getAccount();
    }
}

import com.encap.Account;
public class AccountTest {
    public static void main(String[] args) {
        Account ac = new Account("aq",30,"abcdef");
        System.out.println(ac.info());
    }
}

inherit

Inheritance can solve code reuse. When multiple classes have the same properties and methods, the parent class can be abstracted from these classes, and these same properties and methods can be defined in the parent class. All subclasses do not need to redefine these Attributes and methods only need to extendsdeclare inheritance from the parent class.

Inherit Basic Grammar

class 子类 extends 父类{

}

  1. Subclasses automatically have the properties and methods defined by the parent class
  2. Parent class is also called super class, base class
  3. subclass

detail

  1. Subclasses inherit all properties and methods, but private properties cannot be directly accessed in subclasses, they must be accessed through public methods
  2. The subclass must call the constructor of the parent class to complete the initialization of the parent class
  3. When creating a subclass object, no matter which constructor of the subclass is used, the no-argument constructor of the parent class will always be called by default. If the parent class does not provide a no-argument constructor, it must be in the constructor of the subclass Use super to specify which constructor of the parent class completes the initialization of the parent class.
  4. If you want to specify to call a constructor of the parent class, call it explicitly
  5. When super is used, it needs to be placed on the first line of the constructor
  6. Both super() and this() can only be placed on the first line of the constructor, so these two methods cannot coexist in a constructor
  7. All classes in java are subclasses of the Object class
  8. The call of the parent class constructor is not limited to the direct parent class, it will be traced back to the Object class
  9. A subclass can only inherit at most one parent class, that is, a single inheritance mechanism in java
  10. Inheritance cannot be abused, subclasses and parent classes must satisfy the logic of is a Cat is an Animal Cat extends Animal

back to details

Return information by lookup relationship

  1. First check whether the subclass has this attribute
  2. If the subclass has this attribute and can access it, return the information
  3. If the subclass does not have this attribute, it depends on whether the parent class has this attribute
  4. If there is no parent class, follow the rule of (3) and continue to find the parent class until Object

Exercises, com.extend.ExtendsExercise.java

Write the Computer class, including CPU, memory, hard disk and other attributes, and the getDetails method is used to return the detailed information of the Computer

Write a PC subclass, inherit the Computer class, and add unique attributes [brand]

Write a NotePad subclass, inherit the Computer class, and add unique attributes [demo color]

Write the Test class, create PC and NotePad objects in the main method, assign values ​​to the unique attributes in the object, and assign values ​​​​to the attributes inherited from the Computer class, and use the method and print out the information

package com.extend;

public class ExtendsExercise {
    public static void main(String[] args) {
        PC pc = new PC("i7", "1G", "100G", "huawei");

        NotePad np = new NotePad("i7", "2G", "200G", "green");

        System.out.println(pc.getDetails());
        System.out.println(np.getDetails());
    }
}

class Computer {
    private String CPU;
    private String cache;
    private String disk;

    public Computer(String CPU, String cache, String disk) {
        this.CPU = CPU;
        this.cache = cache;
        this.disk = disk;
    }

    public String getDetails() {
        return "信息为:CPU: " + CPU + " cache: " + cache + " disk: " + disk;
    }
}

class PC extends Computer {
    private String brand;

    public PC(String CPU, String cache, String disk, String brand) {
        super(CPU, cache, disk);
        this.brand = brand;
    }

    public String getDetails() {
        return super.getDetails() + " brand: " + brand;
    }
}

class NotePad extends Computer {
    private String color;

    public NotePad(String CPU, String cache, String disk, String color) {
        super(CPU, cache, disk);
        this.color = color;
    }
}

super keyword

super represents a reference to the parent class, used to access the properties, methods, and constructors of the parent class

basic grammar

//1.访问父类的属性,但不能访问父类private属性
    super.属性名;
//2.访问父类的方法,但不能访问父类private方法
    super.方法名(参数列表);
//3.访问父类的构造器
    super(参数列表);//只能放在构造器第一句

usage details

  1. The benefits of calling the constructor of the parent class (the division of labor is clear, the properties of the parent class are initialized by the parent class, and the properties of the subclass are initialized by the subclass)
  2. When the subclass has the same name as the member (property, method) in the parent class, in order to access the members of the parent class, you must pass super. If there is no duplicate name, using super, this, and direct access has the same effect
  3. The access of super is not limited to the direct parent class. If there are members with the same name in the grandpa class and this class, you can also use super to access the members of the grandpa class. If there are members with the same name in multiple base classes (superior classes), use super Access follows the principle of proximity

Comparison of super and this

no point of difference this super<br>
1 access properties Access the attributes in this class, if there is no such attribute in this class, continue to search from the parent class Access properties in the parent class
2 call method Access the method in this class, if there is no such method in this class, continue to search from the parent class Direct access to methods in the parent class
3 call constructor Calling the constructor of this class must be placed in the first line of the constructor Calling the parent class constructor must be placed in the first line of the subclass constructor
4 special represents the current object Access parent class object in subclass

Method override/override (override)

Method overriding (overriding) means that the subclass has a method that has the same name, return type, and parameters as a method of the parent class. Then we say that the method of the subclass overrides the method of the parent class.

Method override details

Method rewriting must meet the following conditions:

  1. The parameter method name of the subclass method must be exactly the same as the parent class parameter method name
  2. The return type of the subclass method is the same as the return type of the parent class method, or a subclass of the parent class return type
  3. Subclass methods cannot narrow the access rights of parent class methods

Comparison of method overriding and overloading

name Range of occurrence method name parameter list return type modifier<br>
overload This category must be the same At least one type, number or order is different no request no request
rewrite parent-child class must be the same must be the same The method overridden by the subclass returns the same type as the parent class, or its subclass Subclass methods cannot narrow the access scope of parent class methods

Method Override Exercise, com.override.OverrideExercise.java

  1. Write a Person class, including attributes (private name, age), constructor, method say (return self-introduction)
  2. Write a Student class, inherit the Person class, add id, score attribute/private, and constructor, and define the say method
  3. In main, create Person and Student objects respectively, and call the say method to output self-introduction
package com.override;

public class OverrideExercise {
    public static void main(String[] args) {
        Person person = new Person("a", 11);
        Student student = new Student("a", 12, 1, 100);
        System.out.println(person.say());
        System.out.println(student.say());
    }
}

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String say() {
        return "姓名:" + name + " 年龄:" + age;
    }
}


class Student extends Person {
    private int id;
    private int score;

    public Student(String name, int age, int id, int score) {
        super(name, age);
        this.id = id;
        this.score = score;
    }

    public String say() {
        return super.say() + " id:" + id + " 分数:" + score;
    }
}

polymorphism

A method or object has many forms.

  1. Rewriting and overloading embody polymorphism
  2. Object polymorphism, com.poly.PolyObject.java
    1. An object's compile type and run type can be inconsistent
    2. The compilation type is determined when the object is defined and cannot be changed
    3. The type of operation can be changed
    4. When compiling the type, look at the definition = left, and when running the type, look at = the right Animal animal = new Dog() animal When compiling the type is Animal, the running type is Dog animal = new CatI() The running type of animal becomes Cat, and the compiling type is still Animal
package com.poly;

public class PolyObject {
    public static void main(String[] args) {
        Animal animal = new Dog();
        animal.cry();
        animal = new Cat();
        animal.cry();
    }
}

class Animal {
    public void cry() {
        System.out.println("Animal cry()...");
    }
}

class Cat extends Animal {
    @Override
    public void cry() {
        System.out.println("Cat cry()...");
    }
}

class Dog extends Animal {
    @Override
    public void cry() {
        System.out.println("Dog cry()...");
    }
}

polymorphic details

  • Upward transformation

    • Essence: The reference of the parent class points to the object of the subclass

      • Animal animal = new Dog();
    • Syntax: parent class type reference name = new subclass type();

    • Features:

      • The compile type is on the left, and the running type is on the right
      • All members of the parent class can be called
      • Cannot call specific members in subclasses
      • The final running effect depends on the specific implementation of the subclass
  • Downward transformation

    • Syntax: subclass type reference name = (subclass type) parent class reference;

      • Cat cat = (Cat) animal;
    • Only the reference of the parent class can be forcibly transferred, but the object of the parent class cannot be forcibly transferred

    • It is required that the reference of the parent class must point to an object of the current target type

    • After downcasting, all members in the subclass type can be called

  • Attributes are not overridden

  • instanceOf, used to determine whether the running type of the object is XX type or a subtype of XX type

  • Upward transformation and downward transformation of Java

java dynamic binding mechanism

When calling an object method, the method will be bound to the memory address/running type of the object

When calling object properties, there is no dynamic binding mechanism, where to declare and where to use

polymorphic application

polymorphic array

The definition type of the array is the parent class type, and the actual element type stored in it is the subclass type

polymorphic parameters

The formal parameter type of the method definition is the parent class type, and the actual parameter type is allowed to be the subclass type

Detailed Explanation of Object Class

equals method

== vs. equals

  1. ==: It can judge both the basic type and the reference type
  2. ==: If the basic type is judged, the judgment is whether the values ​​are equal
  3. ==: If you judge the reference type, you judge whether the addresses are equal, that is, judge whether they are the same object
  4. equals: It is a method in the Object class, which can only judge the reference type
  5. The default judgment is whether the addresses are equal, and this method is often rewritten in subclasses to judge whether the contents are equal. Such as Integer, String

hashCode method

  1. Improve the efficiency of containers with hash structures
  2. Two references, if they point to the same object, have the same hash value
  3. Two references, if they point to different objects, have different hash values
  4. The hash value is mainly based on the address number, and the hash value cannot be completely equivalent to the address
  5. In collections, hashCode is also overridden

toString method

Returns: full class name + @ + hexadecimal hash value.

Subclasses often rewrite the toString method to return the attribute information of the object

finalize method

  1. When the object is recycled, the system automatically calls the finalize method of the object, and subclasses can override this method to do some operations to release resources
  2. When is it recycled? When an object does not have any references, the jvm considers the object to be a garbage object, and will use the garbage collection mechanism to destroy the object. Before destroying the object, the finalize method will be called first.
  3. The call of the garbage collection mechanism is determined by the system, and the garbage collection mechanism can also be activated actively through System.gc()

Project Lingqiantong

Project Requirements Description

Using Java to develop Lingqiantong project, you can complete functions such as revenue entry, consumption, viewing details, and exiting the system

Project code implementation

SmallChangeSys.java completes the basic functions, completes the basic functions

Code Implementation Improvements

  1. When the user enters 4 to exit, a prompt "Are you sure you want to exit" y/n is given, and the correct y/n must be entered, otherwise, the input command is looped until y or n is entered
  2. When income is recorded and consumed, judge whether the amount is reasonable
  3. Modify the process-oriented code to an object-oriented method, write SmallChangeSysOOP.java and use SmallChangeSysApp.java to complete the test

Homework for this chapter

1. Define a Person class {name, age, job}, initialize the array of Person objects, there are 3 person objects, and sort them according to age from large to small, prompt, use bubble sort. Homework01.java

2. Write the teacher class, Homework02.java

  1. Requires attributes name, age, possalary
  2. Write a business method, introduce(), to output a teacher's information
  3. Write three word categories for teachers: professor category, associate professor category, and lecturer category. Salary level: Professor: 1.3, Associate Professor: 1.2, Lecturer: 1.1. Override the introd() method in the three subclasses
  4. Define and initialize a teacher object, call the business method, and realize the background printing of the basic information of the object
package com.homework;

public class Homework01 {
    public static void main(String[] args) {
        Person[] pArr = new Person[3];
        pArr[0] = new Person("a", 30, "driver");
        pArr[1] = new Person("b", 20, "student");
        pArr[2] = new Person("c", 40, "teacher");
        Person temp;
        for (int i = 0; i < pArr.length; i++) {
            for (int j = i; j < pArr.length; j++) {
                if (pArr[i].getAge() > pArr[j].getAge()) {
                    temp = pArr[i];
                    pArr[i] = pArr[j];
                    pArr[j] = temp;
                }
            }
        }
        for (int i = 0; i < pArr.length; i++) {
            System.out.println(pArr[i].toString());
        }
    }
}

class Person {
    private String name;
    private int age;
    private String job;

    public Person(String name, int age, String job) {
        this.name = name;
        this.age = age;
        this.job = job;
    }
    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 String getJob() {
        return job;
    }
    public void setJob(String job) {
        this.job = job;
    }
    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", job='" + job + '\'' +
                '}';
    }
}

Guess you like

Origin blog.csdn.net/weixin_65656674/article/details/126413444