Object oriented (classes and objects)

Posted by warpdesign on Mon, 17 Jan 2022 13:01:41 +0100

Learning objectives

1,understand Java Object oriented thinking
2,Master the definition and use of classes and objects
3,Master the difference between member variables and local variables
4,Master the definition and use of methods
5,Master the parameter transfer of the method
6,Master the definition and use of method overloading

Chapter 1 object oriented idea

1.1 introduction of object-oriented idea

Java language is an object-oriented programming language, and object-oriented idea is a programming idea. Under the guidance of object-oriented idea, we use java language to design and develop computer programs.
The object here generally refers to all things in reality, and each thing has its own attributes and behavior. The object-oriented idea is the design idea of abstracting the attribute characteristics and behavior characteristics of things with reference to real things in the process of computer programming and describing them as computer events.
It is different from the process oriented idea, which emphasizes that the function is realized by calling the behavior of the object, rather than operating and realizing it step by step.

Summary of object-oriented thinking:
    1.Process oriented:When you want to implement a function,You need to do it yourself,Handle every detail
    2.object-oriented:When you want to implement a function,Don't care about specific implementation steps,Only care about the results,Find a class with this function,Help us
    3.Object oriented thinking
        (1)Object oriented programming is based on the idea of process oriented programming.
        (2)Process oriented:The emphasis is on the steps of each function
        (3)object-oriented:The emphasis is on the object,Then the function is called by the object
    4.characteristic
        (1)It is a thought more in line with our thinking habits
        (2)You can simplify complex things
        (3)The role has changed,Changed us from executors to commanders

1.2 object oriented example

wash clothes:

  • Facing the process: take off the clothes – > find a basin – > put some washing powder – > add some water – > soak for 10 minutes – > knead – > wash the clothes – > wring dry – > dry
  • Object oriented: take off clothes – > turn on the automatic washing machine – > throw clothes – > button – > hang them

difference:

  • Process oriented: emphasize steps.

  • Object oriented: emphasize the object. The object here is the washing machine.

characteristic:

Object oriented thinking is an idea more in line with our thinking habits. It can simplify complex things and turn us from executor to commander. Object oriented language contains three basic features, namely encapsulation, inheritance and polymorphism.

1.3 class and object introduction

Looking around, you will find many objects, such as tables, chairs, classmates, teachers and so on. Tables and chairs belong to office supplies, and teachers and students are human beings. So what is a class? What is an object?

1.3.1 what are classes

  • Class: a set of collections with similar properties and behaviors. It can be regarded as the template of a kind of things, and the attribute characteristics and behavior characteristics of things are used to describe this kind of things.

In reality, describe a class of things:

  • Attribute: is the state information of the thing.
  • Behavior: is what the thing can do.

Example: human.

Attributes: name, age, gender, height, etc.
Behavior: eating, sleeping, working, etc.

1.3.2 what is an object

  • Object: it is the concrete embodiment of a kind of things. An object is an instance of a class (an object is not looking for a girlfriend), and it must have the properties and behavior of such things.

In reality, an example of a class of things: a person.

Example: a person.

Attribute: Zhang Sanfeng, 120, male, 175.
Behavior: eat, sleep, practice martial arts.

1.3.3 relationship between class and object

  • Class is the description of a class of things, which is abstract.

  • An object is an instance of a class of things and is concrete.

  • Class is the template of object, and object is the entity of class.

In the following figure, boy s and girl s are classes, and each person is an object of this class:

Chapter 2 classes and objects

In the Java language, it refers to the classes and objects in the real world, designs the language with the idea of object-oriented, divides some things according to classes, and then manages them in the form of objects.

2.1 definition of class

Syntax:

Access modifier class Class name {
   //Member variable attribute characteristics
   //Member method behavior properties
}

explain:

  • Define class: it is to define and manage a real class in the Java language for a business or real class. Referring to the real class, there are two key characteristics: attribute and behavior, so the class in Java also includes attribute and behavior.
  • **Access permission modifier: * * refers to the keywords in Java that control whether the current class is visible and who is visible, including public, protected, default and private (specific functions will be described later). Generally, the permission modifier of the class is public.
  • **Class: * * defines the keyword of the Java class.
  • **Class name: * * is the specific class we want to create. Give us a name that we know by name. For example, Student, Teacher, etc.
  • **Member variable: * * it is almost the same as the previously defined variable (which can be compared with the properties of real objects). It's just that the location has changed. In a class, outside a method.
  • Member method: it can display the behavior of objects by analogy, describing what behavior all objects of this class can have and how to act (the previous main() method is an example).

Example:

public class Student {
  	// Member variable
  	String username;//full name
    int age; //Age

    //Member method
    //Learning methods
    public static void study() {
       System.out.println("study hard and make progress every day");
    }
    // Methods of running
    public void run(String username,int distance) {
       System.out.println(username+" I ran away today"+distance+"m");
    }
}

2.2 object creation

Java classes are available, but they are only an abstract concept. If you want to use them, you must create concrete objects one by one.

Syntax:

Class name object name = new Class name();

At present, as long as you create a class object in Java, you can use the new keyword.

Use objects to access members in a class:

Object name.Member variables;
Object name.Member method();

Example:

public class StudentTest {
  public static void main(String[] args) {
    // Create object format: class name object name = new class name ();
    Student s = new Student();
    System.out.println(s); //com.hopu.classobject.Student@15db9742
  }	
}

Object creation and basic use:

public class StudentTest {
	  public static void main(String[] args) {
	    // Create object format: class name object name = new class name ();
	    Student s = new Student();
	    System.out.println(s); //com.hopu.classobject.Student@15db9742

	    // Direct output of member variable values
	    System.out.println("full name:"+s.username); //null
	    System.out.println("Age:"+s.age); //0
	    System.out.println("----------");

	    //Assign values to member variables
	    s.username = "Sasaki";
	    s.age = 32;

	    // Output the value of the member variable again
	    System.out.println("full name:"+s.username); //Sasaki
	    System.out.println("Age:"+s.age); //32
	    System.out.println("----------");

	    // Call member method
	    s.study(); // "Study hard and make progress every day"
	    s.run("tom",123); // run
	  }	
}

As can be seen from the above example results, after the object is created, the member variables of the object are directly output without error, and there are some default initialization values. See the following table for details. This is the same as the default initialization value of the array explained earlier.

data typeDefault value
Basic typeInteger (byte, short, int, long)0
float, double0.0
Character (char)'\u0000'
booleanfalse
reference typeArray, class, interfacenull

2.3 class and object exercises

Define mobile phone class:

public class Phone {
  // Member variable
  String brand; //brand
  int price; //Price
  String color; //colour

  // Member method
  //phone
  public void call(String name) {
    System.out.println("to"+name+"phone");
  }

  //send message
  public void sendMessage() {
    System.out.println("Mass texting");
  }
}

Define test class:

public class PhoneTest {
  public static void main(String[] args) {
    //create object
    Phone p = new Phone();

    //Output member variable value
    System.out.println("Brand:"+p.brand);//null
    System.out.println("Price:"+p.price);//0
    System.out.println("Color:"+p.color);//null
    System.out.println("------------");

    //Assign values to member variables
    p.brand = "hammer";
    p.price = 2999;
    p.color = "brown";

    //Output the member variable value again
    System.out.println("Brand:"+p.brand);//hammer
    System.out.println("Price:"+p.price);//2999
    System.out.println("Color:"+p.color);//brown
    System.out.println("------------");

    //Call member method
    p.call("Zixia");
    p.sendMessage();
  }
}

2.4 object memory analysis

1. Memory diagram of an object calling a method:

From the above figure, we can understand that the method running in stack memory follows the principle of "first in, last out, last in, first out". The variable p points to the space in the heap memory, looks for the method information, and executes the method.

However, there are still problems. When creating multiple objects, if a method information is saved inside each object, it will be a waste of memory, because the method information of all objects is the same. So how to solve this problem? Please see the diagram below.

2. Memory diagram of two objects calling the same method:

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-oYr5Cvfy-1626778941231)(imgs/image-20200611154207055.png)]

When an object calls a method, it looks for method information in the class according to the method tag (address value) in the object. In this way, even if there are multiple objects, only one copy of method information is saved to save memory space.

2.5 member variables and local variables

When I introduced the definition of class, I introduced that the Java class includes two core parts: member variables and methods. In Java, we give variables different names according to their definition positions. As shown in the figure below:

explain:

  • Different positions in the class focus
    • Member variable: in class, outside method
    • Local variable: in method or on method declaration (formal parameter)
  • The scope of action is different and the focus is different
    • Member variables: in classes
    • Local variables: in method
  • Different focus of initialization value
    • Member variables: have default values
    • Local variable: no default value. You must first define, assign, and then use
  • Different locations in memory
    • Member variables: heap memory
    • Local variables: stack memory
  • Different understanding of life cycle
    • Member variable: exists with the creation of the object and disappears with the disappearance of the object
    • Local variable: exists with the method call and disappears with the method call

Summary:

The difference between local variables and member variables
1.Different positions in the class [ key ]
	Member variable: in class, outside method
	Local variable: in a method or on a method declaration(Formal parameters)
2.Different locations in memory (understand)
	Member variables: heap memory
	Local variables: stack memory
3.Different life cycles (understanding)
	Member variable: exists with the creation of the object and disappears with the disappearance of the object
	Local variable: exists with the method call and disappears with the method call
4.Different initialization values [ key points ]
	Member variables: have default values
	Local variable: no default value. You must first define, assign, and then use
5.Different scope of action [ key ]
	Member variables: in classes
	Local variables: in method

Chapter 3 methods

3.1 method overview

3.1.1 Java method introduction

When we learn operators, we create a new class and main method for each operator separately. We will find that writing code in this way is very cumbersome and there are too many repeated codes. Can we avoid these repeated codes? We need to use methods to implement them.

At the same time, combined with the object-oriented design idea of Java language introduced earlier, a class will include behavior, and this behavior is a dynamic implementation. Therefore, methods can also be used to implement it.

  • Method: organize the code blocks with independent functions into a whole and make them have a code set with special functions.

When you need this function, you can call it. This not only realizes the reusability of code, but also solves the phenomenon of code redundancy, but also encapsulates the behavior characteristics of a class.

3.1.2 method definition

Syntax:

Access modifier static modifier return value type method name (parameter type parameter name),Parameter type parameter name...){
    Execute code...	
   	return Return statement;
}

explain:

  • Access modifier: similar to the permission modifier used in the previous class definition, it specifies the available range of the method.
  • **Static modifier: * * defines how the method can be accessed, and its keyword is static. If there is a static keyword in front of the method, you can access it directly by using the class without creating a class object; If there is no static keyword, you must create a specific object to access the method.
  • Return value type: the return result type after the method is executed. If the method has no return value, use the void keyword; If there is a return value, it should be determined according to the type of the return value. What type of return value is used.
  • **Method name: * * name the method we defined, which meets the specification of identifier and is used to call the method.
  • Parameter type: the defined method may need to pass a dynamic data, which can be received with method parameters. The parameter type indicates that it defines the parameter types allowed to be received by the current method.
  • **Parameter name: * * corresponds to the parameter type one by one. It is used to receive the parameter value passed when calling the method. Parameter types and parameter names are collectively referred to as parameter lists. Multiple parameter lists can be directly separated by commas ",".
  • **Execution code: * * is what a method does.
  • **Return: * * the result to be returned after the execution code in the method is executed. If there is a return value, it is represented by "return returned result"; If there is no result to return, you can directly use a return keyword or even omit it.

Example:

public class MethodTest {
	//1. Normal no parameter, no return value method
	public void print() {
		System.out.println("This is a normal no parameter, no return value method");
		return;  // No return value method. The return keyword can be omitted
	}
	// 2. Ordinary methods with parameters and no return value
	public void printSum(int a,int b) {
		int sum=a+b;
		System.out.println(a+"And"+"b The sum of is:"+sum);
	}
	// 3. Common methods with parameters and return values
	public int getMax(int a,int b) {
		int max=a>b ? a : b;
		return max;
	}
	// 4. Static methods with parameters and return values
	public int getAbs(int a) {
		if(a<0) {
			return -a;
		}else {
			return a;
		}
	}
}

3.1.3 method practice

1. Define a method with no parameters and no return value

  • **Requirements: * * define a common method in which the "hello world" statement is printed.
  • realization:
public class MethodTest2 {
	public void print() {
		System.out.println("hello world");
	}
}

2. Define a static method with parameters and return values

  • **Requirements: * * define a static method, receive two int type parameters, use this method to find the n-th power of a and return the result (here, only calculate that a and N are positive integers).
  • realization:
	// 2. Static method with parameter and return value
	public static int pow(int a,int n) {
		int result=1;
		for (int i = 0; i < n; i++) {
			result*=a;
		}
		return result;
	}

3.1.4 precautions for defining methods

  • Methods cannot be nested

Methods can only be defined in classes, and methods cannot be nested in methods.

public class MethodDemo {
    public static void main(String[] args) {

    }
    public static void methodOne() {
		public static void methodTwo() {
       		// Compilation errors will be caused here!!!
    	}
    }
}
  • The return value type must be the same as or smaller than the return value type range of the return statement, otherwise the compilation fails.
// The return value type is required to be int
public static int getSum() {
    return 5;// Correct, int type
    return 1.2;// Error, type mismatch
    return true;// Error, type mismatch
}
  • You cannot write code after return. Return means that the method ends. All subsequent code will never be executed. It is invalid code.
public static int getSum(int a,int b) {
  	return a + b;
  	System.out.println("Hello World");// Error. return has ended. It will not be executed here. Invalid code
}
  • void indicates that there is no return value. You can omit return or write return separately without data
public class MethodDemo {
    public static void main(String[] args) {

    }
    public static void methodTwo() {
        return;	 // return can also be omitted, and no other code can be written later
    }
}

3.2 detailed explanation of main () method

In Java, the main() method is the entry method of Java application, that is, when the program is running, the first method to execute is the main() method. This method is very different from other methods. For example, the name of the method must be main, the method must be of public static void type, and the method must receive parameters of a string array.

The definition format of main method is usually fixed as follows:

public class Demo {
	public static void main(String[] args) {
		System.out.println("Hello Word");
	}
}

Illustration:

explain:

  • Why is it public

    Java has designed several access modifiers, including private, default, protected and public. Any method or variable declared public in Java can be accessed from outside the class. The JVM accesses the main method obviously not inside the class, so the main method needs to be defined as a public method.

  • Why is it static

    Static can make it more convenient for the JVM to call the main method without calling through an object. What we know about the static keyword is that the method modified by the static keyword can be accessed directly through the class name instead of creating an instance. The static modified methods and variables are stored in the method area of the virtual machine, not in the heap memory. So, the same is true for virtual machines. If the main method is defined as static, the virtual machine can call the main method without creating an instance after the program is started.

  • Why is there no return value (void)

    void indicates that the main method has no return value. The reason for the lack of return value is that Java does not need the main method to return exit information to the operating system. If the main method exits normally, the exit code of the Java application is 0, indicating that the program has been successfully run.

  • main

    The name of main cannot be changed so that the JVM can recognize the starting point of program operation. The main method can be overloaded, and the overloaded main method will not be executed. The main method is the starting point of the initial thread of the program, and any other thread is started by this thread. There are two kinds of threads inside the JVM: non daemon thread and daemon thread. The main method belongs to non daemon thread. The daemon thread is usually used by the JVM itself. Java programs can also indicate that their own thread is a daemon thread. When all non daemon threads in the program terminate, the JVM exits. You can also use the Runtime class or system Exit() to exit.

  • String [] args

    String[] args is the only place in the main method that can be changed! Args is the abbreviation of arguments. It is just the default name of a variable. You can write it habitually, but it can also be changed. As long as you comply with the naming rules, you can write whatever you want. Today, when using integrated development tools, String[] args is more like a decoration. Many beginners don't know its role. In fact, it is a parameter group passed in by the program running.

3.3 method call

In the above section, only various types of methods are defined in the class, but it is impossible to execute and view the effect. Therefore, the method call needs to be further explained here.

3.3.1 basic introduction to method call

As described earlier, method is actually a behavior of a class. Therefore, to invoke a specific behavior, you need to specify which specific object method to execute. Therefore, the standard method call should first create an object, and then use the object to call a specific method.

Example:

// First create a specific Student object
Student s = new Student();
// Next, use the object to call the concrete method
s.run("tom",123);

be careful:

As described earlier, we can use the static keyword to define a method as a static method when defining a method (the static keyword will be described in detail later). At this time, if you want to call a method in a class, you can omit the step of creating an object and call it directly with the class name.

// For static methods in a class, you can call them directly with the class name
Student.study();

In the following sections, in order to facilitate the demonstration and explanation of method calls with different parameters and return values, we will directly describe the static static method defined in the current class by default. If it is a common method in other classes, you need to create an object in advance and then use the object to call the method.

3.3.2 method call without parameter and return value

Call format:

  • Method calls of different classes
Object name.Common method name();
Class name.Static method name();
  • Method call of similar method
this.Method name();   // this keyword can be omitted

Example:

// 1. Call specific methods of other classes
Student s = new Student();
s.run("tom",123);
Student.study();

// 2. Call the relevant methods in this class
method();

Illustration:

public static void main(String[] args) {
    //Call the defined method
    method();
}
//Defines a method that is called by the main method
public static void method() {
  	System.out.println("This is a method");
}

**Summary: * * when each method is called and executed, it will enter the stack memory and have its own independent memory space. After the internal code of the method is called, it will pop from the stack memory and disappear.

3.3.3 method call with parameters and no return value

Call format:

  • Method calls of different classes
Object name.Common method name(Parameter 1,Parameter 2);
Class name.Static method name(Parameter 1,Parameter 2);
  • Method call of similar method
this.Method name(Parameter 1,Parameter 2);   // this keyword can be omitted

Example:

printSum(5,6);

Illustration:

public static void main(String[] args) {
    //Call the defined method
    printSum(5,6);
}
//Defines a method that is called by the main method
public static void printSum(int a,int b){
	int sum = a + b;
    System.out.println(sum);
}

3.3.4 method call with return value

Call format:

Data type variable name = Method name ( parameter ) ;

Example:

int result = getSum(5,6);

be careful:

The return value of a method is usually received using a variable, otherwise the return value will be meaningless.

Illustration:

3.4 parameter transfer of method

It can be understood that when we want to call a method, we will pass the specified value to the parameters in the method, so that the parameters in the method have the specified value and can use the value to operate in the method. This transfer method is called parameter transfer.

  • Here, when defining a method, the variables in the parameter list are called formal parameters
  • When a method is called, the value passed to the method is called the actual parameter

3.4.1 basic data type as method parameter

Example:

public class Demo01Args {
	public staticvoid main(String[] args) {
		// Define variables
		inta = 10;
		intb = 20;
		System.out.println("a:" + a + ",b:" + b);// a:10,b:20
		change(a, b);
		System.out.println("a:" + a + ",b:" + b);// a:10,b:20
	}

	public static void change(int a, int b) { // a=10,b=20
		System.out.println("a:" + a + ",b:" + b);// a:10,b:20
		a *= 10; // a=100;
		b *= 10;// b=200;
		System.out.println("a:" + a + ",b:" + b);// a:100,b:200
	}
}

**Note: * * the change of formal parameters does not affect the actual parameters.

Illustration:

3.4.2 reference data type as method parameter

Example:

public class Demo02Args {
	public static void main(String[] args) {
		// Define array
		int[] arr = { 10, 20};
		System.out.println(arr[0]);
        System.out.println(arr[1]);
		System.out.println("----------------");
		change(arr);
		System.out.println(arr[0]);
        System.out.println(arr[1]);
	}

	public static void change(int[] arr) {
		arr[0] = arr[0]*10;
        arr[1] = arr[1]*10;
	}
}

**Note: * * reference type, as a method parameter, changes in formal parameters will affect the actual parameters.

Illustration:

Chapter 4 method overloading

4.1 heavy load concept

  • Method overloading: more than one method with the same name is allowed in the same class, as long as their parameter lists are different, regardless of modifiers and return value types.
    • Multiple methods in the same class
    • Multiple methods have the same method name
    • Multiple methods have different parameters, different types or different quantities
  • be careful
    • Parameter list: different numbers, data types and orders.
    • Overloaded method call: the JVM calls different methods through the parameter list of the method.

Exercise: determine which methods are overloaded relationships.

public static void method(){}
public static void method(int a){}
static void method(int a,int b){}
public static void method(double a,int b){}
public static void method(int a,double b){}
public void method(int i,double d){}
public void method(){}
public static void method(int i,int j){}

4.2 method overload exercise

  • **Requirements: * * three methods are defined in a class. One method receives two int type parameters and returns the summation result; One method receives two double types and directly prints the summation result; A method receives three int type parameters and returns the sum result.
  • code:
public class MethodOverloadTest {
	// 1. Method summation of 2 int type parameters
	public int getSum(int a,int b) {
		return a+b;
	}
	// 2. Method summation of two double type parameters
	public void getSum(double a,double b) {
		System.out.println(a+b);
	}
	// 2. Method summation of three int type parameters
	public int getSum(int a,int b,int c) {
		return a+b+c;
	}
}

Topics: Java