12, Classes and objects

Posted by lvitup on Mon, 07 Feb 2022 23:24:24 +0100

Level 1: what is a class and how to create it

Task description
This related task: create a class and an object, and call the properties and methods of the object.

Relevant knowledge
In order to complete this task, you need to master: 1. What are classes and objects; 2. How to define classes; 3. How to create objects and use their properties and methods.

What is a class
Class: a class is a template that describes the behavior and properties of a class of objects.
Object: an object is an instance of a class with properties and behaviors.

for instance:

Man is a "class", Xiao Ming is the "object", girl / boy is a class, and your girlfriend / boyfriend is an object. The attributes of this object include: name, gender and age; Behaviors include: eating, sleeping, studying, etc.

In Java, the state of an object is an attribute, and the behavior is reflected through methods, that is, objects in Java are generally composed of attributes and behaviors.

How to define classes
You need to use class to declare the name of this class.
For example:

class Student{
//Declare that this is a student class
}

There are age, name and gender attributes in the student category. The methods are eating, sleeping and learning.

Create an object and use its properties and methods

Output:

My name is Xiao Ming. This year: 12
 Xiao Ming is having dinner
 sleep
 study

To sum up, we can find that the formula used to create the object is:

Class name object name = new Class name();

Assign values to the properties of the object:

Object name.Attribute name = value;

Use the properties of the object:

Object name.Attribute name

Method of calling object:

Object name.Method name();

Programming requirements
According to the prompt, supplement the code at the beginning end of the editor on the right:

Declare a Dog class, add three String type attributes to the Dog class, namely name, color and variety, and define two methods, eat and run.

Create a Dog object named wuhuarou in the main method, and set the name to streaky pork, color to brown and variety to Alaska.

So that the eat method of calling wuhuarou object can output gnawing bone, and the run method can output running with bone in its mouth.

See the test instructions for specific output requirements.

Test description
Test input: None

Expected output: use Chinese colon

Name: streaky pork, coat color: Brown, variety: Alaska
 Gnaw a bone
 Run with a bone in your mouth

code implementation

package step1;
public class Test {
	public static void main(String[] args) {
		/********** Begin **********/
		Dog wuhuarou=new Dog();
		wuhuarou.name="streaky pork";
		wuhuarou.color="brown";
		wuhuarou.variety="Alaska";//Set the properties of the Dog object
		//Output properties
		System.out.println("name:" + wuhuarou.name    + ",Coat color:" + wuhuarou.color   + ",varieties:" +wuhuarou.variety );
		//Call method
         wuhuarou.eat();
		 wuhuarou.run();
		/********** End **********/
	}
}
//The Dog class is defined here
/********** Begin **********/
  class Dog{
	  String name;
	  String color;
	  String variety;
	 void  eat(){
		  System.out.println("Gnaw a bone");
	  }
	  void run(){
		  System.out.println("Run with a bone in your mouth");
	  }
  }
/********** End **********/

Level 2: construction method

Task description
This related task: create objects and define parameterless construction methods and parameterless construction methods for objects.

Relevant knowledge
In order to complete the task of this level, you need to master: 1 What is the construction method, 2 How to define and call construction methods.

What is a construction method
Construction method: the method that will be called when the object is created. When the object is created, that is, when it is new, the construction method will be called automatically.

for instance:

Output:

I was called

How to define and use construction methods
How to define the construction method? What is the difference between the construction method and the method we learned before?
See the picture:

See the difference?
OK, let me summarize and see if you can find the corresponding code in the figure above:

The construction method can have parameters or no parameters;

The constructor has no return value and does not need to declare the void keyword;

Constructor name must be the same as class name.

Next, I create a Student object in the main method. The code is as follows:

public static void main(String[] args){
        Student stu = new Student();
        Student stu1 = new Student("Zhang San");
}

Do you think there will be output? If so, what will the output result be? If not, what do you think is the reason?

Programming requirements
According to the prompt, supplement the code at the beginning end of the editor on the right:

Create a Person class, define a non parametric construction method and a parametric construction method for the Person class. There are two String type parameters name and sex in the main method.

Call the parameterless construction method output: a person is created;

When calling the parametric construction method, the corresponding result shall be output according to the input data. For example, if the input is Zhang San, male, the output is: Name: Zhang San, gender: male, which is created.

Test description
Test input: Zhang Fugui, unknown
Expected output:

A man was created
 Name: Zhang Fugui, gender: unknown, created

Summary:
Construction method of object:
When an object is created, that is, when it is new, the constructor will be called automatically.

Object initialization can be done in the construction method, which has the following characteristics;

1. The construction method is different from the object method. It is called automatically when the object is created;
2. The construction method can have parameters or no parameters;
3. The construction method has no return value;
4. The constructor name must be the same as the class name;
5. If the defined class does not declare a constructor, the object uses an empty constructor by default when it is created.

code implementation

package step2;

import java.util.Scanner;

public class Test {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String name = sc.next();
		String sex = sc.next();
		/********** Begin **********/
		//Two constructors are used to create the Person object  
		Person a=new Person();
        Person b=new Person(name,sex);
		
	}
}

//Create a Person object and create two construction methods
/********** Begin **********/
class Person{
		  public Person(){
			   System.out.println("A man was created");
		  }
		  public Person(String name,String sex){
			  	System.out.print("full name:"+name+",Gender:"+sex+",Was created");
		  }
	  }

/********** End **********/

Level 3: This keyword

Task description
This related task: use this keyword to set the member variable of the object.

Relevant knowledge
Let's start with a piece of code:

Output result:

Incoming name:Li Si age:10
student attribute name:Zhang San age:18

From the above results, we can find a problem. In the construction method, the name and age are not set successfully. The values of the name attribute and age attribute of the stu object are defined by default.

How to solve this problem? You need to learn two knowledge points: 1 What is a member variable; 2.this keyword.

What is a member variable
The member variable is the attribute of the object:

this keyword
About this keyword, you just need to remember that it refers to yourself. This stands for yourself, this Property accesses its own property, and this() accesses its own parameterless construction method.

Example 1: this attribute

Example 2: this Property, this()

Output:

I am
 Zhang San

It can be found that if we put the above this If name = name is changed to name = name, the final result will be:

I am
null

this() calls Person's own parameterless constructor, this Name accesses the name of the Person object itself, while name in the method parameter represents the value passed in by the method.

After learning the usage of this keyword, will the problem encountered at the beginning of this pass be solved?

Programming requirements
The code has been written in the editor on the right, but the output result is not satisfactory. Please modify the code according to your knowledge so that it can output the following results:

name: baby
age: 45
sex: female

Test description
Test input:

baby,45,female

Expected output:

name: baby
age: 45
sex: female

code implementation

package step3;

import java.util.Scanner;

public class Test {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String name = sc.next();
		int age = sc.nextInt();
		String sex = sc.next();
		Person p = new Person(name,age,sex);
		p.display();
	}
}

class Person{
	String name = "Zhang San";
	int age = 18; 
	String sex = "male";
	/********** Begin **********/

	public Person(String name,int age,String sex){
		this(age);
		this.name = name;
		this.sex = sex;
	}
	
	public Person(int age){
		this.age = age;
	}
	
	public void display(){
		String name = "Li Si";
		int age = 11;
		String sex = "male";
		System.out.println("name: " + this.name);
		System.out.println("age: " + this.age);
		System.out.println("sex: " + this.sex);
	}


	/********** End **********/
}

Level 4: class and object practice

Task description
This off task: write a class for "nameless powder", and write the construction method and member variables of this class.

Relevant knowledge
Concept of package
Previously, we defined classes and methods in one file, but in the actual development process, we certainly can't use one file to write all the code.
How to solve this problem?

Duang, the package is on stage. The package is like a folder in our windows system, but the package is dedicated to storing code files.

The main function of package code is to classify files.

If a class is defined under a package, you need to declare the package name when defining the class, otherwise the program will report an error.

For example:

Programming requirements
I have created two files for you. One is wumingfen Java, the other is test Java, you need to switch files and write code in two files to complete this task.

Write a class for "nameless powder": class WuMingFen requirements:

There are three attributes: face code: String theMa powder component (two): int quantity whether there is soup: boolean likeSoup;

Write a construction method to simplify the initialization process, such as:

WuMingFen f1 = new WuMingFen("beef",3,true);;

Overload the construction method, so that the initialization process can be diversified:

  WuMingFen f2 = new WuMingFen("beef",2);;

How to make the powder object constructed by the following statements be sour and spicy noodles, 2 Liang and soup?

 WuMingFen f3 = new WuMingFen();;

Write a common method: check(), which is used to check whether the powder meets the requirements. That is, print the three attributes of the object on the console.

Test description
I will test the code you write:

Test input:

Beef, 3, true

Expected output:

Noodle size: beef, amount of flour: 3 Liang, with soup or not: true
 Noodle size: beef, amount of flour: 3 Liang, with soup or not: false
 Noodle size: hot and sour, amount of powder: 2 liang, with soup or not: true

Test input:

Sanxian, 1, true

Expected output:

Noodle size: three delicacies, amount of powder: 1 liang, with soup or not: true
 Noodle size: three delicacies, amount of powder: 1 liang, with soup or not: false
 Noodle size: hot and sour, amount of powder: 2 liang, with soup or not: true

Mouse over to switch files:

code implementation

package step4;
import java.util.Scanner;
public class Test {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String theMa = sc.next();
		int quantity = sc.nextInt();
		boolean likeSoup = sc.nextBoolean();
		/********** Begin **********/
		WuMingFen f1=new WuMingFen(theMa,quantity,likeSoup);
		//Use the construction method of three parameters to create a WuMingFen object named f1
		WuMingFen f2=new WuMingFen(theMa,quantity,false);//The two parameter construction method is used to create the WuMingFen object named f2
		WuMingFen f3=new WuMingFen(); //Use the parameterless construction method to create a WuMingFen object named f3
		//Call the check methods of the three classes respectively
	    f1.check();
		f2.check();
		f3.check();
		/********** End **********/	
	}
}
/********** Begin **********/
//Add the package name step4 here
    class WuMingFen{
		String theMa="sour and hot";
		int quantity=2;
		boolean likeSoup=true;
   public WuMingFen(){  
    }
  public WuMingFen(String a,int b, boolean c){
        theMa=a;
		quantity=b;
		likeSoup=c;	
	}
	public WuMingFen(String a,int b){
				 theMa=a;
				quantity=b;
			}	
	public void check(){
		 System.out.print("Face code:"+theMa+",Amount of powder:"+quantity+"Two, whether to bring soup:"+likeSoup);
		System.out.println();
			}
}
/********** End **********/	

Level 5: static keyword

Task description
This related task: use the static keyword to set the properties of methods and variables.

Relevant knowledge
In order to complete the task of this level, you need to master: 1 What is the function of static keyword? 2 How to use the static keyword.

What is the static keyword
We often contact the static keyword, but we haven't discussed what it is and what specific role it plays. What is the static keyword and what is its use?

Static means static. It is a modifier, just like an adjective. It is used to describe classes, variables and methods.

Static modifies a variable, which becomes a static variable, and modifies a method, which becomes a static method,

static keyword is convenient for calling (method / variable) without creating an object.

Function of static keyword
static keyword can be understood as an adjective. It is generally used to describe classes, methods, variables and code blocks. Another function is to statically guide packages. In this chapter, we will only discuss its three uses.

1. Modify variables
To access the properties of an object without using the static keyword:

Use the static keyword to access the properties of an object:

Note: if the member variable of a class is modified by static, all objects of the class share this variable. No matter how many objects this class instantiates, there is only one copy of its static variables.
For example:

Output:

Li Si
 Li Si
 Li Si

2. Modification method

The method decorated with static keyword is called static method. We have used the static method. I believe you are already familiar with it. That is, you can use it directly without creating objects.
For example:

be careful:

Static methods cannot use non static variables of classes;

Static methods can call static methods directly, but ordinary methods can only be called through the instance of the object.

3. Static code block

Let's first look at the running effect of a static code block:

Output result:

I was called

In the figure above, static {} is a static code block.

We didn't write any code in the main method, but when running, the program will still output that I was called. Therefore, we can find that the static code block can run independently without relying on the main method.

You only need to remember one sentence about static code blocks: run when the class is loaded and only run once.

The calling of variables and methods in static code blocks also follows the rule we mentioned earlier, that is, only static attributes and methods can be called directly.

Programming requirements
Now there is an exception in the code in the editor. Please use the knowledge learned in this level to modify the code on the right so that it can output the following results:

hello educoder
 My name is Chu Liuxiang
 I like to be in educoder Study on java

Note: the static keyword cannot be used to modify local variables in Java. Why? Because this is what the boss said, we as little brothers can't listen.

code implementation

package step5;
public class Test {
	/********** Begin **********/
	static String name = "Chu Liuxiang";
	static{
		System.out.println("hello educoder");
	}	
	public static void main(String[] args) {
		System.out.println("My name is" + name);
		study();
	}
	public static void study(){
		System.out.println("I like to be in educoder Study on java");
	}
	/********** End **********/
}

Topics: Java