当前位置:网站首页>Day 9 (this keyword and experiment)
Day 9 (this keyword and experiment)
2022-07-24 19:17:00 【to be__】
this: Represents the current object or the object currently being created , This class attribute can be called , Call this class method or constructor .
In the method of a class , You can use this. Property name or this. Method To call the properties and methods of the current object , Usually omitted , When the formal parameter name of a method in a class has the same name as the attribute name , You have to use this. Attribute name to operate .( The constructor of class is similar )
1、 Call this class property
public class BookTest {
public static void main(String[] args) {
Book book = new Book();
book.setBookName("The Ordinary World");
book.setBookPrice(66);
System.out.println(book.getBookName());
System.out.println(book.getBookPrice());
}
}
class Book{
private String bookName;
private int bookPrice;
// The method parameter name is the same as the attribute name in the class
public void setBookName(String bookName){
// utilize this. Attribute name
this.bookName = bookName;
}
public String getBookName(){
return this.bookName;
}
public void setBookPrice(int bookPrice){
this.bookPrice = bookPrice;
}
public int getBookPrice(){
return this.bookPrice;
}
}2、 Invoking Constructors
(1) Inside the constructor of the class , By using this( Parameter list ) To call other constructors of the current class
(2) Cannot be used inside the constructor this To call yourself , And there can only be one at most this Call statement
(3) Use this( Parameter list ) The call constructor statement must be placed on the first line of the constructor method
public class BookTest {
public static void main(String[] args) {
Book book = new Book("The Ordinary World",66);
System.out.println(book.info());
}
}
class Book{
private String bookName;
private int bookPrice;
public Book(){
System.out.println(" Parameterless constructors ");
}
public Book(String bookName){
this();
this.bookName = bookName;
}
public Book(String bookName,int bookPrice){
this(bookName);
this.bookPrice = bookPrice;
}
public String info(){
return "the name of the book is:" + this.bookName + ", the price of the book is:" + this.bookPrice;
}
}3、 experiment
Experiment 1 :
establish Boy and Girl Two classes , And create private properties name、age, And declare set/get Methods and corresponding constructors ,marry、shout、compare For the methods in their respective classes .(- Express private,+ Express public)

//Boy.java The code is as follows :
public class Boy{
private String name;
private int age;
// Declare a two parameter constructor
public Boy(String name, int age) {
this.name = name;
this.age = age;
}
// Statement set get Method
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
// Statement marry Method
public void marry(Girl girl){
System.out.println("marry:"+girl.getName());
}
// Statement shout Method
public void shout(){
if(this.age >= 22){
System.out.println("you can marry");
}else{
System.out.println("you're too young to marry");
}
}
}
//Girl.java The code is as follows :
public class Girl {
private String name;
private int age;
public Girl(String name, int age) {
this.name = name;
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void marry(Boy boy){
System.out.println("marry to:"+boy.getName());
boy.marry(this); //this: Who is calling marry Method who is the current object
}
// Compare The current object And The object passed in Age of
public int compare(Girl girl){
return this.age-girl.age;
}
}//main() The code is as follows :
public class BoyGirlTest{
public static void main(String[] args) {
Boy boy = new Boy("Mike",22);//Boy Class instantiation
boy.shout();// call Boy Class method
Girl girl = new Girl("Marry",20);//Girl Class instantiation
girl.marry(boy);// call Girl Class method
Girl girl1 = new Girl("Lily",24);
int result = girl.compare(girl1);// Compare girl And girl1 In the age of girl call ( For the current object )
if (result > 0){
System.out.println(girl.getName()+" older ");
}else if (result < 0){
System.out.println(girl1.getName()+" older ");
}else{
System.out.println(girl.getName()+" and "+girl1.getName()+" The same age ");
}
}
}
Experiment two :
establish Customer Classes and Account class , And realize the function of deposit and withdrawal , And display customer account information .
(1)Customer The class code is as follows :
public class Customer {
private String firstName;
private String lastName;
private Account account;
// Declare a two parameter constructor
public Customer(String f, String l) {
firstName = f;
lastName = l;
}
// Statement related set get Method
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public void setAccount(Account account) {
this.account = account;
}
public Account getAccount() {
return account;
}
}
(2)Account The class code is as follows :
public class Account {
private int id;
private double balance;
private double annualInterestRate;
// Declare a three parameter constructor
public Account(int id, double balance, double annualInterestRate) {
this.id = id; // user id
this.balance = balance; // User balance
this.annualInterestRate = annualInterestRate; // Annual interest rate
}
// Declare properties related set get Method
public void setId(int id) {
this.id = id;
}
public void setAnnualInterestRate(double annualInterestRate) {
this.annualInterestRate = annualInterestRate;
}
public void setBalance(double balance) {
this.balance = balance;
}
public int getId() {
return id;
}
public double getAnnualInterestRate() {
return annualInterestRate;
}
public double getBalance() {
return balance;
}
// Declare the method of withdrawal
public void withdraw(double amount){
if(this.balance < amount){
System.out.println(" Lack of balance , Withdrawal failed ");
}else{
this.balance -= amount;
System.out.println(" Successfully deposited :"+amount);
}
}
// State how to save money
public void deposit(double amount){
if (amount > 0) {
this.balance += amount;
System.out.println(" Successfully removed :"+amount);
}
}
}
(3) A functional test
public class AccountCustomerTest {
public static void main(String[] args) {
//Customer Class instantiation
Customer c1 = new Customer("Jane","Smith");
//Account Class instantiation
Account a1 = new Account(1000,2000,0.0123);
// Put the object c1 The account object of is set as object a1 ( Connect the two classes )
c1.setAccount(a1);
// adopt getAccount Method calls the save method
c1.getAccount().deposit(100);
// Call the withdrawal method
c1.getAccount().withdraw(960);
c1.getAccount().withdraw(2000);
// Print customer account information
System.out.println("Customer ["+c1.getLastName()+","+c1.getFirstName()+" has a account: id is "+a1.getId()
+", annualInterestRate is "+ a1.getAnnualInterestRate()*100 +"%, balance is "+a1.getBalance());
}
}
Output :

Experiment three :
establish Customer1、Account1、Bank Classes and related methods , And write BankTest Test related functions
(1)Customer1 The class code is as follows :
public class Customer1 {
private String firstName1;
private String lastName1;
private Account1 account1;
public Customer1(String f,String l) {
this.firstName1 = f;
this.lastName1 = l;
}
public String getFirstName1() {
return firstName1;
}
public String getLastName1() {
return lastName1;
}
public void setAccount1(Account1 account1) {
this.account1 = account1;
}
public Account1 getAccount1() {
return account1;
}
}
(2)Account1 The code is as follows :
public class Account1 {
private double balance;
public Account1(double init_balance) {
this.balance = init_balance;
}
public double getBalance() {
return balance;
}
public void withdraw(double amt) {
if (this.balance < amt) {
System.out.println(" Lack of balance , Withdrawal failed ");
} else {
this.balance += amt;
System.out.println(" Successful withdrawals :" + amt + ", The current balance is : " + this.balance);
}
}
public void deposit(double amount) {
if (amount > 0) {
this.balance += amount;
System.out.println(" Deposit success :" + amount + ", The current balance is : " + this.balance);
} else {
return;
}
}
}(3)Bank The class code is as follows :
public class Bank {
// Create private Customer1 An array of objects Store multiple customers
private Customer1[] customers = new Customer1[10]; //10*3
private int NumberOfCustomer;
// Create a parameterless constructor
public Bank(){
}
public void addCustomer(String f,String l){
// Create a new Customer object And call the constructor to assign the initial value
Customer1 c1 = new Customer1(f,l);
//customerIndex: Index in the object array where the customer is located
int customerIndex = this.NumberOfCustomer++;
// Will create a new object c1 Put it into the object array
this.customers[customerIndex] = c1;
}
public int getNumberOfCustomers(){
return this.NumberOfCustomer;
}
// Return value as object
public Customer1 getCustomer(int index){
// If the index meets the condition
if (index >= 0 && index < this.NumberOfCustomer){
// return index Where you are
return this.customers[index];
}else{
return null;
}
}
}(4)BankTest test
public class BankTest {
public static void main(String[] args) {
//Bank Instantiation
Bank bank = new Bank();
// Add customers
bank.addCustomer("Zhang","GuoHua");
// Create customer
bank.getCustomer(0).setAccount1(new Account1(2000));
// Withdraw money
bank.getCustomer(0).getAccount1().withdraw(500);
// Deposit money
bank.getCustomer(0).getAccount1().deposit(10000);
bank.getCustomer(0).getAccount1().withdraw(20000);
// Get the specified customer balance information
double theRest= bank.getCustomer(0).getAccount1().getBalance();
System.out.println(" Customer "+bank.getCustomer(0).getLastName1()+" The balance of is : "+theRest);
System.out.println("-----------------------------------");
bank.addCustomer("DaHua","OuYang");
// Get the current number of customers
System.out.println(" The current number of bank customers is : "+bank.getNumberOfCustomers());
}
}边栏推荐
- MySQL index principle and query optimization "suggestions collection"
- Mysql database, de duplication, connection
- SATA protocol OOB essay
- pyhanlp安装教程
- Hidden Markov model HMM
- Leetcode402 remove K digits
- Those gods on Zhihu reply
- Biopharmaceutical safety, power supply and production guarantee
- What are the benefits of knowledge management in enterprises?
- Pay close attention! List of the latest agenda of 2022 open atom open source Summit
猜你喜欢

Leetcode652 finding duplicate subtrees

The difference between static method and instance method

PWN learning

Meshlab & PCL ISS key points

In the spring of domestic databases

This visual analysis library makes it easy for you to play with data science!

Literature reading: gopose 3D human pose estimation using WiFi

Reading notes of XXL job source code

Principle and application of database
![[JVM learning 04] JMM memory model](/img/8c/0f76be122556301a5af140e34b55f4.png)
[JVM learning 04] JMM memory model
随机推荐
Techempower web framework performance test 21st round results release --asp Net core continue to move forward
PCIe link initialization & Training
Clion configuring WSL tool chain
Thread theory knowledge
多线程与并发编程常见问题(未完待续)
JVM方法调用
Common problems of multithreading and concurrent programming (to be continued)
MySQL8.0学习记录20 - Trigger
Environment preparation of Nacos configuration center
MySQL1
Sqoop
Crazy God redis notes 11
Solve the problem of disconnection due to long idle time after SSH login
卷积神经网络感受野计算指南
Mysql数据库,去重,连接篇
Principle and application of database
Decision tree_ ID3_ C4.5_ CART
Colon sorting code implementation
PWN learning
第4章 复合类型