Chapter 4 Object Orientation (I)
4.6 One of the object-oriented characteristics: encapsulation and hiding
Why does encapsulation need to be introduced and embodied? What does encapsulation do and what does it mean? I need to use the washing machine, just press the switch and wash mode. Is it necessary to know the inside of the washing machine? Is it necessary to touch the motor? I’m going to drive…
Our program design pursues “high cohesion, low coupling”. High cohesion: The internal data manipulation details of the class are done by itself, without external interference; Low coupling: Only a few methods are exposed for use.
Hide the internal complexity of objects and expose only simple interfaces. Easy to call outside, so as to improve the system scalability, maintainability. In layman’s terms, hide what needs to be hidden and expose what needs to be exposed. That’s the idea of encapsulation.
* When we create a class of objects, we can pass "object". Property "to assign a value to an object's property. Here, assignment is constrained by the data type and storage scope of the * attribute. But beyond that, there are no other constraints. In practice, however, we often need to place additional constraints on assigning * to attributes. This condition is not reflected in the property declaration, we can only add the condition through the method. For example, setLegs * in the meantime, we need to prevent the user from using the "object" again. Property "to assign a value to a property. Declare the property as private * --. In this case, encapsulation is applied to the property. * * We privatized the class attributes and provided public methods to get (getXxx) and set (setXxx) * * Extension: Encapsulation: ① above, ② singleton pattern ③ private method * */
public class AnimalTest {
public static void main(String[] args) {
Animal a = new Animal();
a.name = "Rhubarb";
// a.age = 1;
// a.legs = 4;//The field Animal.legs is not visible
a.show();
// a.legs = -4;
// a.setLegs(6);
a.setLegs(-6);
// a.legs = -4;//The field Animal.legs is not visiblea.show(); System.out.println(a.name); System.out.println(a.getLegs()); }}class Animal{
String name;
private int age;
private int legs; // Number of legs
// Set the attributes
public void setLegs(int l){
if(l >= 0 && l % 2= =0){
legs = l;
}else{
legs = 0; }}// Get attributes
public int getLegs(a){
return legs;
}
public void eat(a){
System.out.println("Animal feeding.");
}
public void show(a){
System.out.println("name = " + name + ",age = " + age + ",legs = " + legs);
}
// Provide get and set methods on the attribute age
public int getAge(a){
return age;
}
public void setAge(int a){ age = a; }}Copy the code
Understanding and testing of four permission modifiers
Java permission modifiers public, protected, (default), and private precede a class’s member definition to restrict access to members of that class.
Only public and default(the default) can be used for class permission modifications. ” The public class can be accessed anywhere. ” The default class can only be accessed by classes inside the same package.
The Order class
/* * 3, the encapsulation of the need for permission modifier. There are four types of permissions: (in descending order)private, default, protected, public * 2.4 Types of permissions that modify classes and their internal structures: properties, methods, constructors, inner classes * 3. In particular, four permissions can be used to modify the inner structure of a class: attribute, method, constructor, inner class * To modify a class, you can only use: default, public * summary encapsulation: Java provides four permission modifiers to modify the inner structure of a class, the method to reflect the visibility of the class and the inner structure of the class. * * /
public class Order {
private int orderPrivate;
int orderDefault;
public int orderPublic;
private void methodPrivate(a){
orderPrivate = 1;
orderDefault = 2;
orderPublic = 3;
}
void methodDefault(a){
orderPrivate = 1;
orderDefault = 2;
orderPublic = 3;
}
public void methodPublic(a){
orderPrivate = 1;
orderDefault = 2;
orderPublic = 3; }}Copy the code
OrderTest class
public class OrderTest {
public static void main(String[] args) {
Order order = new Order();
order.orderDefault = 1;
order.orderPublic = 2;
// Outside the Order class, private structures are not callable
// order.orderPrivate = 3;//The field Order.orderPrivate is not visible
order.methodDefault();
order.methodPublic();
// Outside the Order class, private structures are not callable
// order.methodPrivate();//The method methodPrivate() from the type Order is not visible}}Copy the code
OrderTest class for different packages of the same project
import github.Order;
public class OrderTest {
public static void main(String[] args) {
Order order = new Order();
order.orderPublic = 2;
After leaving the Order class, the private structure, the default declaration structure, is not callable
// order.orderDefault = 1;
// order.orderPrivate = 3;//The field Order.orderPrivate is not visible
order.methodPublic();
After leaving the Order class, the private structure, the default declaration structure, is not callable
// order.methodDefault();
// order.methodPrivate();//The method methodPrivate() from the type Order is not visible}}Copy the code
Encapsulation exercises
/* * 1. Create a program that defines two classes: the Person and PersonTest classes. * The definition is as follows: setAge() is used to set a person's legal age (0-130), and getAge() is used to return the person's age. * * /
public class Person {
private int age;
public void setAge(int a){
if(a < 0 || a > 130) {// throw new RuntimeException(" Incoming data is invalid ");
System.out.println("Incoming data is illegal");
return;
}
age = a;
}
public int getAge(a){
return age;
}
// Never write like this!!
public int doAge(int a){
age = a;
returnage; }}Copy the code
The test class
/* * Instantiate the Person object B in the PersonTest class. * Call the setAge() and getAge() methods to experience Java encapsulation. * /
public class PersonTest {
public static void main(String[] args) {
Person p1 = new Person();
// p1.age = 1; // Failed to compile
p1.setAge(12);
System.out.println("Age :"+ p1.getAge()); }}Copy the code
4.7 Constructors (Constructors)
Constructor understanding
Constructor (); constructor (); constructor (); Create object * * 2. Initialize object properties * * 2. If no constructor for the class is displayed, the system provides a constructor for empty parameters by default. * 2. Define the constructor's format: * Permission modifier class name (parameter list) {} * 3. Multiple constructors defined in a class constitute overloads on each other. * 4. Once the constructor for the class is defined, the system no longer provides the default null parameter constructor. * 5. A class must have at least one constructor */
public class PersonTest {
public static void main(String[] args) {
// Create an object for the class :new + constructor
Person p = new Person(); //Person() that's the constructor
p.eat();
Person p1 = new Person("Tom"); System.out.println(p1.name); }}class Person{
/ / property
String name;
int age;
/ / the constructor
public Person(a){
System.out.println("Person()......");
}
public Person(String n){
name = n;
}
public Person(String n,int a){
name = n;
age = a;
}
/ / method
public void eat(a){
System.out.println("People eat.");
}
public void study(a){
System.out.println("People learn"); }}Copy the code
Exercise 1
/* 2. Add a constructor to the Person class as defined above, and use the constructor to set everyone's age property to 18. * * /
public class Person {
private int age;
public Person(a){
age = 18; }}public class PersonTest {
public static void main(String[] args) {
Person p1 = new Person();
System.out.println("Age :"+ p1.getAge()); }}Copy the code
Ex 2
/* create a Person object and initialize the age and name attributes of the object. * /
public class Person {
private int age;
private String name;
public Person(a){
age = 18;
}
public Person(String n,int a){
name = n;
age = a;
}
public void setName(String n){
name = n;
}
public String getName(a){
return name;
}
public void setAge(int a){
if(a < 0 || a > 130) {// throw new RuntimeException(" Incoming data is invalid ");
System.out.println("Incoming data is illegal");
return;
}
age = a;
}
public int getAge(a){
returnage; }}public class PersonTest {
public static void main(String[] args) {
Person p2 = new Person("Tom".21);
System.out.println("name = " + p2.getName() + ",age = "+ p2.getAge()); }}Copy the code
Practice 3
/* * Write two classes, TriAngle and TriAngleTest, where TriAngle declares private base and height, and public methods access private variables. In addition, provide the necessary constructors for the class. Another class uses these common methods to calculate the area of a triangle. * * /
public class TriAngle {
private double base;/ / bottom side
private double height;/ / high
public TriAngle(a){}public TriAngle(double b,double h){
base = b;
height = h;
}
public void setBase(double b){
base = b;
}
public double getBase(a){
return base;
}
public void setHeight(double h){
height = h;
}
public double getHeight(a){
returnheight; }}public class TriAngleTest {
public static void main(String[] args) {
TriAngle t1 = new TriAngle();
t1.setBase(2.0);
t1.setHeight(2.5);
/ / t1. Base = 2.5; //The field TriAngle.base is not visible
/ / t1. Height = 4.3;
System.out.println("base : " + t1.getBase() + ",height : " + t1.getHeight());
TriAngle t2 = new TriAngle(5.1.5.6);
System.out.println("面积 : " + t2.getBase() * t2.getHeight() / 2); }}Copy the code
Summarize the process of attribute assignment
/* * Summary: the order in which attributes are assigned * * ① default initialization * ② explicit initialization * ③ constructor assignment * ④ through "object. Method "or" object. Attribute, assign * * the order of the above operations :① - ② - ③ - ④ * */
public class UserTest {
public static void main(String[] args) {
User u = new User();
System.out.println(u.age);
User u1 = new User(2);
u1.setAge(3); System.out.println(u1.age); }}class User{
String name;
int age = 1;
public User(a){}public User(int a){
age = a;
}
public void setAge(int a){ age = a; }}Copy the code
The use of a JavaBean
/* * Javabeans are reusable components written in the Java language. * > class is a * > public * > has an attribute and a corresponding GET and set methods * */
public class Customer {
private int id;
private String name;
public Customer(a){}public void setId(int i){
id = i;
}
public int getId(a){
return id;
}
public void setName(String n){
name = n;
}
public String getName(a){
returnname; }}Copy the code
UML class diagram (Got it!!
)
1.+ indicates public type, – indicates private type, and # indicates protected type 2. Method type (+, -) Method name (parameter name: parameter type) : return value type
4.8 Keyword: Usage of this
This invokes properties, methods, and constructors
This modifies and calls properties, methods, and constructors * * 2. This modifies properties and methods: * this is the current object, or the object currently being created. * * 2.1 In class methods, we can use the "this. attribute "or "this". Method "to call the current object properties and methods. * Usually, we choose to omit "this." In particular, if the method parameter has the same name as the class attribute, we must explicitly use "this "*. ", indicating that the variable is an attribute, not a parameter. * * 2.2 In class constructors, we can use either the "this. attribute "or "this." Method "to call the properties and methods of the object being created. * But, more often than not, we choose to omit "this." In particular, if the constructor parameter has the same name as the class attribute, we must explicitly use "this "*. ", indicating that the variable is an attribute, not a parameter. * * this calls the constructor * ① We can explicitly call other overloaded constructors in the class using the "this "method. * ② The constructor cannot call itself with "this ". * ③ If n constructors are declared in a class, at most n-1 constructors use this(parameter list). * ④ "this(parameter list)" must be declared on the first line of the class's constructor! * ⑤ In a constructor of a class, you can only declare at most one "this ". * /
public class PersonTest {
public static void main(String[] args) {
Person p1 = new Person();
p1.setAge(1);
System.out.println(p1.getAge());
p1.eat();
System.out.println();
Person p2 = new Person("jerry" ,20); System.out.println(p2.getAge()); }}class Person{
private String name;
private int age;
public Person(a){
this.eat();
String info = "When initializing a Person, consider the following: 1,2,3,4... (40 lines of code)";
System.out.println(info);
}
public Person(String name){
this(a);this.name = name;
}
public Person(int age){
this(a);this.age = age;
}
public Person(String name,int age){
this(age); // a way to call the constructor
this.name = name;
// this.age = age;
}
public void setNmea(String name){
this.name = name;
}
public String getName(a){
return this.name;
}
public void setAge(int age){
this.age = age;
}
public int getAge(a){
return this.age;
}
public void eat(a){
System.out.println("People eat.");
this.study();
}
public void study(a){
System.out.println("Learning"); }}Copy the code
This practice
Boy class
public class Boy {
private String name;
private int age;
public void setName(String name){
this.name = name;
}
public String getName(a){
return name;
}
public void setAge(int ahe){
this.age = age;
}
public int getAge(a){
return age;
}
public Boy(String name, int age) {
this.name = name;
this.age = age;
}
public void marry(Girl girl){
System.out.println("I want to marry." + girl.getName());
}
public void shout(a){
if(this.age >= 22){
System.out.println("Consider marriage.");
}else{
System.out.println("Study hard."); }}}Copy the code
Girl class
public class Girl {
private String name;
private int age;
public String getName(a) {
return name;
}
public void setName(String name) {
this.name = name;
}
public Girl(a){}public Girl(String name, int age) {
this.name = name;
this.age = age;
}
public void marry(Boy boy){
System.out.println("I want to marry." + boy.getName());
}
/ * * * *@DescriptionCompare the size of two objects *@author subei
* @date9:17:35 am, 21 April 2020 *@param girl
* @return* /
public int compare(Girl girl){
// if(this.age >girl.age){
// return 1;
// }else if(this.age < girl.age){
// return -1;
// }else{
// return 0;
/ /}
return this.age - girl.age; }}Copy the code
The test class
public class BoyGirlTest {
public static void main(String[] args) {
Boy boy = new Boy(romeo.21);
boy.shout();
Girl girl = new Girl("Juliet".18);
girl.marry(boy);
Girl girl1 = new Girl("Zhu Yingtai".19);
int compare = girl.compare(girl1);
if(compare > 0){
System.out.println(girl.getName() + "Big");
}else if(compare < 0){
System.out.println(girl1.getName() + "Big");
}else{
System.out.println("The same"); }}}Copy the code
Experiment 1: account_customer.pdf
The Account class
public class Account {
private int id; / / account
private double balance; / / the balance
private double annualInterestRate; / / apr
public void setId(int id) {}public double getBalance(a) {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public double getAnnualInterestRate(a) {
return annualInterestRate;
}
public void setAnnualInterestRate(double annualInterestRate) {
this.annualInterestRate = annualInterestRate;
}
public int getId(a) {
return id;
}
public void withdraw(double amount) { / / make a withdrawal
if(balance < amount){
System.out.println("Insufficient balance, withdrawal failed.");
return;
}
balance -= amount;
System.out.println("Successfully removed" + amount);
}
public void deposit(double amount) { / / save
if(amount > 0){
balance += amount;
System.out.println("Successful deposit"+ amount); }}public Account(int id, double balance, double annualInterestRate) {
this.id = id;
this.balance = balance;
this.annualInterestRate = annualInterestRate; }}Copy the code
The Customer class
public class Customer {
private String firstName;
private String lastName;
private Account account;
public Customer(String f, String l) {
this.firstName = f;
this.lastName = l;
}
public String getFirstName(a) {
return firstName;
}
public String getLastName(a) {
return lastName;
}
public Account getAccount(a) {
return account;
}
public void setAccount(Account account) {
this.account = account; }}Copy the code
, CustomerTest class
/* * Write a test program. * (1) Create a Customer named Jane Smith with account number 1000, * balance of $2000 and annual interest rate of 1.23%. * (2) Execute on Jane Smith. Deposit 100 yuan and withdraw 960 yuan. And withdraw another 2,000 yuan. Customer [Smith, Jane] has an account: Id is 1000, * annualInterestRate is 1.23%, balance is 1140.0 * */
public class CustomerTest {
public static void main(String[] args) {
Customer cust = new Customer("Jane" , "Smith");
Account acct = new Account(1000.2000.0.0123);
cust.setAccount(acct);
cust.getAccount().deposit(100); / / in 100
cust.getAccount().withdraw(960); / / draw money 960
cust.getAccount().withdraw(2000); / / draw money 2000
System.out.println("Customer[" + cust.getLastName() + cust.getFirstName() + "] has a account: id is "
+ cust.getAccount().getId() + ",annualInterestRate is " + cust.getAccount().getAnnualInterestRate() * 100 + "%, balance is "+ cust.getAccount().getBalance()); }}Copy the code
Experiment 2: Account_Cust… Bank.pdf
The Account class
public class Account {
private double balance;
public double getBalance(a) {
return balance;
}
public Account(double init_balance){
this.balance = init_balance;
}
// Save money
public void deposit(double amt){
if(amt > 0){
balance += amt;
System.out.println("Save successfully"); }}// Withdraw money
public void withdraw(double amt){
if(balance >= amt){
balance -= amt;
System.out.println("Successful withdrawal.");
}else{
System.out.println("Insufficient balance"); }}}Copy the code
The Customer class
public class Customer {
private String firstName;
private String lastName;
private Account account;
public String getFirstName(a) {
return firstName;
}
public String getLastName(a) {
return lastName;
}
public Account getAccount(a) {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
public Customer(String f, String l) {
this.firstName = f;
this.lastName = l; }}Copy the code
Bank class
public class Bank {
private int numberOfCustomers; // Count the number of customers
private Customer[] customers; // Store an array of customers
public Bank(a){
customers = new Customer[10];
}
// Add a client
public void addCustomer(String f,String l){
Customer cust = new Customer(f,l);
// customers[numberOfCustomers] = cust;
// numberOfCustomers++;
customers[numberOfCustomers++] = cust;
}
// Get the number of customers
public int getNumberOfCustomers(a) {
return numberOfCustomers;
}
// Get the client at the specified location
public Customer getCustomers(int index) {
// return customers; // An exception may be reported
if(index >= 0 && index < numberOfCustomers){
return customers[index];
}
return null; }}Copy the code
BankTest class
public class BankTest {
public static void main(String[] args) {
Bank bank = new Bank();
bank.addCustomer("Jane"."Smith");
bank.getCustomers(0).setAccount(new Account(2000));
bank.getCustomers(0).getAccount().withdraw(500);
double balance = bank.getCustomers(0).getAccount().getBalance();
System.out.println(Customer: + bank.getCustomers(0).getFirstName() + The account balance of "is:" + balance);
System.out.println("* * * * * * * * * * * * * * * * * * * * * * * * * * *");
bank.addCustomer("Thousands of miles"."Yang");
System.out.println("Number of bank customers is:"+ bank.getNumberOfCustomers()); }}Copy the code
4.9 Keywords: Use of package and import
Keywords – package
/* * 1. To better implement the management of classes in the project, provide the concept of package * 2. Use package to declare the package to which a class or interface belongs, starting at line 3 of the source file. Packages belong to identifiers and follow the naming rules of identifiers and the specification "by name" * 4. Each "." Once, it represents a layer of file directories. * * Add: You cannot name interfaces or classes with the same name in the same package. * You can name interfaces and classes with the same name in different packages. * * /
public class PackageImportTest {}Copy the code
Introduction to the main packages in the JDK
1.java.lang---- contains some of the core Java language classes, such as String, Math, Integer, System, and Thread, that provide common functionality2Java.net ---- contains classes and interfaces for performing network-related operations.3.java.io---- contains classes that provide a variety of input/output functions.4.java.util---- contains utility classes such as a collection framework class that defines system features, interfaces, and functions related to using a date calendar.5.java.text---- contains classes related to Java formatting6.java.sql---- contains Java classes/interfaces for JDBC database programming7Awt ---- contains classes that make up the abstractwindowtoolkits (abstractwindowtoolkits) that are used to build and manage the graphical user interface (GUI) of applications. B/S C/SCopy the code
MVC Design pattern
MVC is one of the commonly used design patterns, which divides the entire program into three layers: view model layer, controller layer, and data model layer. This design mode of separating program input and output, data processing, and data display makes the program structure flexible and clear, and also describes the communication mode between each object of the program, reducing the coupling of the program.
Keywords – the import
import java.util.*;
import account2.Bank;
* * import: import * 1. Explicitly import classes and interfaces from the specified package * 2 using the import structure in the source file. The declaration is between the package declaration and the class declaration * 3. If you need to import multiple structures, write them side by side * 4. You can use "XXX.*" to import all structures in the XXX package. * 5. Omit this import statement if the class or interface is imported from the java.lang package or from the current package. * 6. If you use a class with the same name under a different package in your code. You need to specify which class is being called using the full class name of the class. * 7. If classes from the java.a package have been imported. So if you want to use classes in subpackages of package A, you still need to import. * 8. Import static: call a static attribute or method from a specified class or interface
public class PackageImportTest {
public static void main(String[] args) {
String info = Arrays.toString(new int[] {1.2.3});
Bank bank = new Bank();
ArrayList list = new ArrayList();
HashMap map = new HashMap();
Scanner s = null;
System.out.println("hello");
UserTest us = newUserTest(); }}Copy the code
The entire Java full stack series is my own notes. Writing is not easy. If you can, give it a thumbs up. ✌