Introduction to Java section 7 classes and objects

Posted by earunder on Sat, 12 Feb 2022 01:12:24 +0100

introduction

  to learn Java, we should not only learn the basic grammar, but also learn the idea of programming, in which we should understand what is "class"? What is "object"? And the most important core idea of Java, object-oriented (oop)! This idea can simplify the complex things in life. It is also used in program development, from the original executor to the commander!
  object oriented is based on process oriented, and both are programming ideas!

  1. **Process oriented * * emphasizes the process and refers to the action of the
    a. Zhao Benshan, a famous sketch of the Spring Festival Gala, said: how many steps do you take to put the elephant in the refrigerator? 1. Open the refrigerator door; 2. Put the elephant in; 3 close the refrigerator door;

  2. Object oriented emphasizes the result, which is the "operation object" to accomplish something.
    a. Order takeout on a platform. Don't worry about how to cook the meal. Don't worry about how to get it. Just wait for the door-to-door delivery.
    b. Ask your girlfriend to wash clothes. You just need to tell her! Don't worry about how to wash it. Just wait for the result.

In the above cases, takeout platforms and girlfriends with laundry are the "objects" of the commander! It is also one of the important ideas of java!

1. What is the object

  in the real world, one thing that can be seen everywhere is the object, which is the entity of things. For example, Jay Chou, apple mobile phone and Beijing Tiananmen Square are all so-called objects. Human beings usually solve problems by simplifying complex things, so they will think about what these objects are composed of? People usually divide objects into two parts: static part and dynamic part

  • Static part: refers to the part that cannot be moved, which is called "attribute". Any object has attributes, such as human height, weight, age and gender.
  • Dynamic part: it refers to some special behaviors: such as human, smiling, speaking, walking and performing actions;

Summary and understanding:
Each has three characteristics: the attribute of the object, the behavior of the object (method), and the identification of the object (memory address value).

  1. Object attributes: used to describe the basic characteristics of an object.
  2. Object behavior: used to describe the action or function of an object.
  3. Object identification: refers to that objects have a unique address in memory to distinguish them from other objects. (memory address value)

Classification is a very natural process for people to understand the world. They will unconsciously classify similar things in daily life, such as human, animal and plant. This kind of people or things is the general name.
Among them, the object is the instantiation of the class and the concrete implementation of the class.

2. What is a class

  class is the general name of the same kind of things. If a specific thing in the real world is abstracted into an object, class is the general name of this kind of object, such as human, birds and poultry.
If Zhang San has a mouth and limbs, he can talk through his mouth and walk through his legs. And basically all humans have the characteristics of speaking and walking. In this way, a class of things with the same characteristics and behavior is called class. The idea of class came into being in this way.

  • You can try to lift a chestnut by yourself!!

Summary and understanding:
A class is a carrier that encapsulates the attributes and behaviors of an object, or a class of entities with the same attributes and behaviors is called a class.

  1. The basic unit in java language is class. Like type
  2. Class is formed by extracting common attributes and behaviors from a class of things.
  3. Class as a design template.
  • Class can only be defined, methods and properties can be initialized, and cannot be assigned twice, or statements can be used in the class! class A{int a; a=1} is not allowed!

In the world of java, there is a saying that everything is an object!! Why do you think it says that!?

3. Relationship between class and object

  1. Computer language describes the real world using attributes + methods (behavior)
  2. First create a class, and then create an object through the class.
    a. A class can create multiple objects.
    b. Objects can be regarded as abstracting a special case from a class of things, and dealing with the problems of such things through this special case. Objects can operate the properties and methods of the class to solve the corresponding problems.
  3. How does the java language describe things?

For example:
a. For example, the class has the name of the class, and the class has the color of the object;

b. Human "class":
An object is an entity that can be seen and touched.

4. Grammatical structure:
a. Steps to define a class;

b. To create an object:

Class name object name = new Class name();

c. Reference object members use "." spot

Object name.attribute
 Object name.Method name();
  1. Create Person class
/**As shown in the figure:
 *     Attribute: name, age
 *     Behavior: singing, eating, falling in love
 */
public class Person {  // 1. Define the class name. The first letter of the class must be capitalized!

    // 2. Write attributes
    String name; //full name
    int age; // Age

    // 3. Definition method
    public void love(){// 3.1 no return value and no parameter
        System.out.println("Hand in hand, kiss your mouth!");
    }


   public String eat(String food){// 3.2 there are return values and parameters
        return "What I eat is"+food;
   }

    //sing
    public void say(String songName){ // 3.3 no return value, with parameters
        System.out.println(songName);
    }

}

3.1 . Create TestPerson test class

public class TestPerson {
    // main program entry
    public static void main(String[] args) {

        // 1. Create an object. The new keyword refers to the variable returned by the instance object p  
        Person p = new Person();
        //2. Jay Chou
        p.age=34;
        P.name="jaychou";

        P.say("Bibian Mushi, bibian Mushi"); // Call singing and pass parameter '.' To call
        // Call meal
        String f = p.eat("Little tiger"); 
        System.out.println(f);  
        // Output properties
        System.out.println("full name"+ p.name+ "\n"+"Age: "+ p.age);
    }
}

3.1 simple analysis object creation process

Person p = new Person(); What does this code do in memory?

  • In fact, this code contains two parts:
    1. Declare Person p=null; This is the process of creating this class. 2 in the second part, instantiate this object, p =new Person(); Equivalent to opening up space in memory;

    The explanation is as follows:
  1. Open up space in the stack memory to store the reference type Person type variable p;
  2. In the heap memory, store new Person(); The properties and methods in are stored in heap memory as a whole, that is, the Person object
  3. The default String type of initialization attribute (member variable) is null, and the int type is 0; Then, after initialization, a unique address value will be generated and saved by pointing to the variable p in the stack memory. If you want to operate the object, you should find it through P!
  • Think of this as a balloon! You can find out where the balloon in the memory is by opening the line in your hand!?

4. Method of class

4.1 General

  method definition: a collection of statements that perform a function together, which can be understood as the behavior of the object.
For example: all cars can run, but the speed of running is different, so the car can run is the behavior method provided by the car! Also, whistle, light, turn with the steering wheel, etc.

4.2 nonparametric method

  1. There are two kinds of parameterless methods of class: parameterless methods with return value type and parameterless methods with return value type.
		a.There is a return value(No parameters) 
			 Permission modifier return value type method name( ){
			
					Execution method body;
					
			         return return type;
			    }
		
		 b.No return value(No parameters) 
		 
		  The permission modifier has no return value type method name( ){
			
			         Execution method body;
			    }
  • If there is a return value, the required data type is returned. The keyword return returns the value type. If the method has no return value, the return type is represented by the keyword void.

4.3 parametric methods

Why use methods with parameters?

  1. In our daily life, there is a prerequisite for completing a certain operation, and data or materials need to be provided,
    a. A skillful woman cannot cook without rice. She can cook without rice.
    b. The juicer squeezes things, puts in the material according to the, and produces the corresponding juice.
  2. The method with parameters can be understood as:
    a. Receive externally provided materials (method parameters).
    b. The method processes the data internally (method logic processing).
    c. Product output (return data type).
		a.There is a return value(With parameters) 
			 Permission modifier return value type method name(Parameter 1,Parameter 2,Parameter 3... ){ 
			
					Execution method body;
					
			         return return type;
			    }
		
		 b.No return value(No parameters) 
		 
		  The permission modifier has no return value type method name(Parameter 1,Parameter 2,Parameter 3... ){
			
			         Execution method body;
			    }
  1. Parameters can have one or more, the same type or different types.
  2. The parameters in the parameter list of method () are called formal parameters; The parameters passed by object · method name () are called: actual parameters; For example: formal parameter String name; Argument: "Jay Chou"

be careful:
The definition of formal parameters should be consistent with the number of arguments and the order of transmission!

4.4 method call

  1. Object name · method name ();
  2. Methods and methods can also be called;

4.5 exercise: find the average score and total score

  1. Suppose there are three courses, and the keyboard receives the scores of three courses. It is required to calculate the total score and average score.
public class ResultDemo {
    // Program entry main
    public static void main(String[] args) {

        //create object
        Result r = new Result();
        // Call method r · method in object
        Scanner input = new Scanner(System.in);
        System.out.println("Please enter your English score:");
        r.english = input.nextDouble();

        System.out.println("Please enter your math score:");
        r.maths = input.nextDouble();

        System.out.println("Please enter your Chinese score");
        r.chinese = input.nextDouble();

        //Call the GPA method
        double avg = r.avg();
        System.out.println("Your GPA is:"+avg);

        //Call summation method
        double sum = r.sum();
        System.out.println("Your total score is: "+sum);

       
    }


}
/**
 * Create a result class
 */
class Result{
    double  english; // English achievement
    double  chinese;  //grade scores of Chinese
    double maths;  // Mathematics achievement


    /*Average value, return value type, no parameter*/
    public double avg(){
        double sum = english+chinese+maths;
        return sum/3;
    }
    /*Summation, return value type, no parameter*/
    public  double sum(){
        double sum = english+chinese+maths;
        return sum;
    }
}

Output result:

Please enter your English score:
80
 Please enter your math score:
20
 Please enter your Chinese score
100
 Your GPA is 66.66666666666667
 Your total score is: 200.0

4.6 exercise: adding users and displays

  1. User definition, user name and method are added; Use array storage
public class Customer {

    // Define an array to store customer names
    String[] names = new String[10];

    //Suppose I had elements in the original array
    {
        names[4] = "Lao Wu next door";
    }

    /*Add addname*/
    public void addName(String name){

        for (int i=0;i<names.length;i++){
            //Logical judgment: if there are elements in the original array, do not overwrite them, otherwise add them! No elements are being added
            if (names[i]==null){
                names[i]=name;
                break; //If you do not jump out, all elements in the array will be the first name actual parameter
            }
        }
    }

    /*Display array*/
    public void showNames(){
        for (int i=0;i<names.length;i++){
            if (names[i]!=null){
                System.out.println(names[i]+" ");
            }
        }
    }

    public static void main(String[] args) {

        Customer c = new Customer();
        //Loop in the name, which is relatively simple
//        for(int i=1;i<=3;i++){
//            System.out.println("please enter the" + i + "personal name:");
//            String name = new Scanner(System.in).next();
//            c.addName(name); // It is equivalent to calling the object three times!
//        }

        // It can be called separately or added circularly
        c.addName("0");
        c.addName("1");
        c.addName("2");
        c.addName("3");
        c.addName("4");

        // Call method to display array information
        c.showNames();
    }
}

Output result:

0 
1 
2 
3 
Lao Wu next door 
4 

4.7 exercise: query whether the user exists (multiple parameters)

  1. The user name can be queried according to the interval; If the query is found, it returns true; otherwise, it returns false; Related cases 4.6
public class Customer {

    // Define an array to store customer names
    String[] names = new String[10];

    //Suppose I had elements in the original array
    {
        names[4] = "Lao Wu next door";
    }

    /*Add addname*/
    public void addName(String name){

        for (int i=0;i<names.length;i++){
            //Logical judgment: if there are elements in the original array, do not overwrite them, otherwise add them! No elements are being added
            if (names[i]==null){
                names[i]=name;
                break; //If you do not jump out, all elements in the array will be the first name actual parameter
            }
        }
    }

    /*Display array*/
    public void showNames(){
        for (int i=0;i<names.length;i++){
            if (names[i]!=null){
                System.out.println(names[i]+" ");
            }
        }
    }

    /*Query the names in the array*/
    public boolean seachName(int begin,int end,String name){
        // Define a query ID
        boolean flag = false;
        for (int i=begin;i<end;i++){
            if (name.equals(names[i])){
//                System.out.println("index:" + i)// Indexes
                flag=true;
                // Reduce the number of cycles
                break; // Jump out when you find it
            }
        }
        return flag;
    }

    public static void main(String[] args) {

        Customer c = new Customer();
        //Loop in the name, which is relatively simple
//        for(int i=1;i<=3;i++){
//            System.out.println("please enter the" + i + "personal name:");
//            String name = new Scanner(System.in).next();
//            c.addName(name); // It is equivalent to calling the object three times!
//        }

        // It can be called separately or added circularly
        c.addName("0");
        c.addName("1");
        c.addName("2");
        c.addName("3");
        c.addName("4");

        // Call method to display array information
        c.showNames();

        // Interval query method
        boolean result = c.seachName(2, 10, "Lao Wu next door");
        System.out.println("The query result is:"+result);
    }
}

Output result:

0 
1 
2 
3 
Lao Wu next door 
4 
Index: 4
 The query result is: true

5. Member variables and local variables

5.1 scope of variable

Remember what variables are? How to declare a variable? Variable type variable name = variable value.

  1. The position of variable declaration can determine the scope of variable, that is, the effective range. How to understand this sentence? We can think of some things in life, such as:
    a. The laws of the people's Republic of China are aimed at people in China. (including Chinese and foreigners)
    b. Girlfriend's mobile content - herself.
    c. Platform member products - only members can buy! Non members can't buy it!

  2. Java declares variables in different positions in classes, their scope and scope of influence are different.

5.2 member variables

  1. In Java, attributes defined in classes are also called member variables.
	a.Location: a variable defined in a class and declared outside a method. It can be used anywhere in this class, that is, it is globally valid!!
	b.Features: no initialization assignment, automatic initialization, with default value; Integer type: 0 by default; String default null;Boolean type boolean Default to false;
	c.Life cycle: when the class disappears, the member variable will disappear GC Garbage collection and cleaning);
public class VarDemo {
    /*Member variables defined in the class and outside the method*/
    String name;    // full name
    int age;   //Age
    double price; //Price
    String adress; // address

    /*The program entry main method is also a method*/
    public static void main(String[] args) {

    }

}

5.3 local variables

  1. Defined in the method, this variable is called a local variable.
	a.Location: a variable defined in a class, within a method, and declared. Only valid in method.
	b.Features: when this variable is used, it must be initialized to allocate memory space, that is, it must be assigned; For example: int num = 8;
	c.Life cycle: the method is created during execution and released after running!
public static void main(String[] args) {
        String  s = "I'm a local variable defined in a method";
        System.out.println(s);   //  Local variables must be used when assigning values;
    }

5.4 summary of differences between member variables and local variables

The difference between the two

 1. Different positions in the class,Member variable:One in class,local variable:One is in the method,for example:if sentence,
 2. Different in memory,Member variable:In the heap,local variable,In stack.
 3. Different life cycles,Member variable:Exists with the creation of objects,Disappear as the object disappears.
    local variable:Exists with method calls,Disappears as the method is called,
 4. Different initialization values,Member variable: Local variable with default value: No default value must be defined,Assignment can only be used.

5.5 test local variables and member variables

  • Look at the scope of the two
public class VarTest {

    String name; // name
    int age;   // Age
    String wechat; // Telephone

    int[] num; // House number

    public String show() {  //The principle of proximity of variables!
        String name ="Like flowers";  
        String s="My name: "+name+"  My age is:"+age;
        return s;
    }


    public static void main(String[] args) {
        //Property cannot be called until an object is created
        VarTest v = new VarTest();

        System.out.println(v.wechat);
        System.out.println(v.num); // Default address value; No point


        // Call method
        String show = v.show();
        System.out.println(show);

        v.num=new int[]{2,3};
//      System.out.println(Arrays.toString(num));   Use reference object v.num
        System.out.println(Arrays.toString(v.num));


        /*Local variable i in loop */
        for (int i=0;i<=10;i++){
            System.out.println(i);
        }
       // System.out.println(i); //  The value of I cannot be used because it is an I local variable defined in a for loop
    }

}

Output result:

null
 Array output: null
 My name: Ruhua my age is: 0
[2, 3]
0
1
2
3
4
5
6
7
8
9
10

6 Summary: bank account exercise

  1. The simulated bank deposit business mainly includes three businesses: query, deposit and withdrawal.
package com.oop.bank;

/**
 * Banking
 */
public class Bank {

    // Account amount
    private double money=0;

    /*
        External query methods
     */
    public double getMoney(){
        return money; //Return amount
    }

    /*
        Deposit business;
        Create a parameterized method with no return value
     */

    public void saveMoney(double cash){
        money = money+cash; // Account amount + money deposited
        //When prompted, the deposit successfully displays the balance, and the display balance method is called;
//        double m = getMoney(); //  Just call the method directly
        System.out.println("Deposit succeeded, your balance is"+getMoney());
    }

    /*
    *Withdrawal method
    *   After withdrawal, the amount is reduced, and there is no need to return a value. Same method of saving money
    * */

        public void quMoney(double cash2){
            //Judge whether the money is enough?
            if (cash2<=money){
                money=money-cash2;
                System.out.println("Withdrawal succeeded, and the balance is:"+getMoney());
            }else{
                System.out.println("Withdrawal failed, insufficient balance");
            }
        }
}
  • Test class BankTest
public class BankTest {
    public static void main(String[] args) {
        Bank bank = new Bank();
//        bank.saveMoney(500);
//        bank.quMoney(300);
        
        // You can also add a do{}while(flag); It's a cycle 
        System.out.println("What business do you want to handle: 1 deposit 2 withdrawal 0 exit");
        //Equivalent judgment
        int num = new Scanner(System.in).nextInt();
        switch (num){
            case 1:
                //TODO
                System.out.println("Please enter your deposit amount:");
                double m = new Scanner(System.in).nextDouble();
                bank.saveMoney(m);
                break;

            case 2:
                System.out.println("Please enter the withdrawal amount:");
                double m2 = new Scanner(System.in).nextDouble();
                bank.quMoney(m2);
                break;
            case 0:
                System.out.println("Thank you for your coming");
                break;
            default:
                System.out.println("Your choice is wrong. Please see the prompt");
                break;
        }

    }
}

Output result:

What business do you want to handle: 1 deposit 2 withdrawal 0 exit
1
 Please enter your deposit amount:
800
 Deposit succeeded. Your balance is 800.0

Topics: Java Back-end