IV. Objects and Classes
4.1 Overview of Object-Oriented Programming
Relationships among 4.1.4 Categories
- Classification: uses a, has a, inheritance (is a)
-
rely on
- Methods of one class manipulate objects of another class
- The most common relationship, the most obvious relationship
- The design should follow the principle of minimizing dependency as much as possible. The lower the dependency, the lower the coupling.
-
polymerization
- One class contains another class.
4.2 Use predefined classes
4.2.1 Objects and Object Variables
1. Object variables
- Definition: Part of a reference variable
-
Be careful
- An object variable does not contain an object, but only refers to an object.
4.3 User-defined Classes
4.3.4 Constructor
-
rule
- Constructor and Similar Name
- Each class can have more than one constructor
- Constructors can have 0 to more than one parameter
- Constructor does not return a value
- The constructor is called with the execution of the new operator and cannot reset the instance domain through the constructor
4.3.5 Implicit and Explicit Parameters
- Implicit parameters: class objects in front of method names, represented by this keyword
-
Explicit parameters: parameters of the incoming method
<! - Realization - >
public void raise(double ByPercent){ double raise = this.salary * ByPercent; } /* conclusion 1.ByPercent For explicit parameters 2.this For implicit parameters, representing class objects */
Advantages of 4.3.6 Packaging
1. Domain Accessor
- Definition: Machine that returns instance domain values
-
Form
- Private Data Domain
- Public Domain Accessor Method
- Public Domain Changer Method
-
Format: public decoration, return value is instance domain value
<! - Realization - >
// Demand: Return Salary Value public class Worker{ private int salary; } // Domain Accessor public int getSalary(){ return salary; }
-
advantage
- Support for modifying internal implementations without affecting other code
- Supports error checking <! - - such as judging whether incoming data is empty - >.
-
Be careful
-
If you need to return a copy of a variable data field, use clone()
<! - Realization - >
class E{ ... public Date getH(){ return (Date)hire.clone(); } }
-
4.4 Static Domain and Static Method
4.4.1 Static Domain
- Definition: Domain modified by static
- Characteristics: Static domain belongs to class, not object. That is, all objects share a static domain.
4.4.2 Static Constant
-
Commonly used static constants
-
Math.PI
<! - Realization - >
// Definition public class Math { public static final double PI = 3.123453454354535345; } // Use public class TestMath { public static void main(String[] args) { int l = 5; double circle = l*l*Math.PI; System.out.println(circle); } }
- System.out
-
4.4.3 Static Method
- Definition: Methods that cannot operate on objects (static methods are methods without this parameter)
-
Use scenarios
- The method does not need to access the object state, and all the required parameters are provided by displaying parameters <! -- such as Math. pow - >.
- Method only needs to access the static domain of the class <! -- such as the get method that returns the content of the static domain - >.
4.4.4 Factory Method
- Definition: Static method pattern that supports the return of expected objects
-
step
- Creating abstract product classes and defining common interfaces <! -- mu lt iple objects in the factory need to be obtained, and variable types of return methods can be unified - > 1.
- Create specific product classes
- Create factory classes, create static methods to return specific product classes
-
External classes call static methods in factory classes to obtain corresponding product objects
<! - Realization - >
// Abstract product class, easy to produce a variety of product types abstract class Product { protected abstract void show(); }
// Specific Product Category 1 public class Product1 extends Product { @Override public void show() { System.out.println("Product1"); } } // Specific Product Category 2 public class Product2 extends Product { @Override public void show() { System.out.println("Product2"); } } // Specific Product Category 3 public class Product3 extends Product { @Override public void show() { System.out.println("Product3"); } }
// Factory class, which returns the corresponding object according to the type of the incoming parameter public class ProductFatory { public static Product getProduct(String s){ switch (s){ default:return null; case "a" :return new Product1(); case "b" :return new Product2(); case "c" :return new Product3(); } } }
// Test class public class TestFactory { public static void main(String[] args) { ProductFatory.getProduct("a").show(); ProductFatory.getProduct("b").show(); ProductFatory.getProduct("c").show(); } } /* output Product1 Product2 Product3 */
-
Pros
- Creating and using instances to decouple
-
Cons
- When an error occurs in the factory class, the whole system is affected.
- In violation of the Open-Close Principle, new classes need to modify the factory logic, and the factory classes will be cumbersome.
4.5 Method Parameters
-
Rule: java calls by value, and the method gets a copy of all parameter values
-
The value of the basic data type cannot be modified.
<! - Realization - >
// Method of modifying values public class Method { public void changeNum(int num){ num = num * 3; } } // Test class public class TestMethodParam { public static void main(String[] args) { int n = 5; Method method = new Method(); System.out.println(n); method.changeNum(n); System.out.println(n); } } /* output 5 5 */ /* conclusion Because num is initialized as a copy of the value of n, modifying num does not affect the value of n */
- Support for modifying the state of object parameters
Cause: A parameter is a copy of an object reference, so it points to an object, and when a change occurs, it modifies the value in the object.
- It is not supported to have object parameters refer to a new object
Reason: Parameters are copies of object references. Modifying references does not affect the original references.
Schematic diagram:
-
4.6 Object Construction
4.6.1 Heavy Load
1. Signature of Method
-
Format: Method name and parameter type
<! - Realization - >
indexOf(int)
4.6.6 Call another constructor
-
Format: Call another constructor in the constructor of the class using this keyword
<! - Realization - >
public class TestCons { private int age; private String name; private TestCons(int aAge) { this.age = aAge; } private TestCons(int aAge , String aName) { this(5); this.name = aName; } public static void main(String[] args) { TestCons testCons = new TestCons(4,"Toyz"); System.out.println(testCons.age); System.out.println(testCons.name); } }
4.6.7 Method of Initializing Data
-
Method
-
Setting values in constructors
<! - Realization - >
private TestCons(int aAge) { this.age = aAge; }
-
Assignment in declaration
<! - Realization - >
private int age = 5;
-
Assignment in initialization blocks (unusual, usually implemented in constructors)
<! - Realization - >
{ int age = 5; }
-
-
Execution order
- All data fields are initialized to default values
- Execute the initialization statement (method 2 above) and the initialization domain (method 3 above) according to the order of declaration in the class.
- Execution constructor (method 1 above)
4.10 Kinds of Design Skills
- Be sure to keep data private
- Be sure to initialize the data
- Don't use too many basic types in classes (use other classes instead)
- Not all domains require separate domain access and modifiers
- Decomposition classes with too much responsibility (or lead to too much coupling)
- Class names and method names can reflect responsibilities
- Prefer immutable classes