It's so long. I'll optimize the structure with the main and sub headings when I'm free
Overview of classes
[overview]
In the previous lesson, we saw different built-in classes. These classes include Scanner class, String class, and some original data type classes, such as integer and double, Integer.parseInt(), Double.parseDouble()
[Primitive types]
There are eight raw data in Java, which are int, byte, short, float, double, Boolean, char and long
When we declare these original types of variables, a fixed size of memory will be allocated to store the values. The fixed memory allocated by each type is different
In short, it is
Raw data types are limited in size and flexibility
[built in class]
Array array
Array is a powerful way to extend the original data type - it allows us to collect variables of the same type under a single variable name, and we can also make arrays of any length
But even for arrays, they can only do the corresponding things for us, and can't do things beyond the scope of its rules
String Strings
A string is an example of the reference type reference type
After declaration, memory will not be allocated to the string until initialization
String type is more powerful than array because it can hold values of any size. String provides methods that can interact with "values", such as String.length()
These (Scanner, String, Integer) are built-in classes in Java. We can also create Java classes to perform specific user-defined tasks
[User Defined Class]
Class is the definition of a class of objects that have the same behavior and the same type of properties
We can think of a class as a template
Let's take a car as an example. For all vehicles, they generally have:
Specific types of motors, colors, a certain number of doors, etc
In addition to having attributes, each class can also perform some user-defined tasks, such as the above car:
We can not only encapsulate the description of the car, but also encode the functions related to the car
The code we can write to capture car properties and functions is called class
In addition, we can also use other objects as attributes
[composition of classes]
1. Class name A class name
There is a convention in writing: the class name should start with a capital letter and be a noun
2. Attributes, instance variable attributes
These variables are used to hold values inside the class, and other objects can also be used as properties
3. Constructor(s)
There should always be a default constructor. This type of constructor has no input parameters. If it is not provided, the JVM will automatically provide one
The constructor name is the same as the class name
4.Getters method (also known as Accessors)
These are user-defined methods that return the values of those properties in the class
5. Changers Setters (also known as Mutators)
Methods for setting and changing property values in classes
6. Functions in the form of methods
There are some methods with special functions
[Object]
An object is an instance of a class and can be considered to be used like any variable
For example, when using the Scanner class, we can create objects of this class by writing the following
Scanner sc= new Scanner(System.in);
After creating the corresponding object, we can use its function. Now we have an instance of Scanner class in our program
[create an example of Class]
Let's start with an example of a java class representing car. Our class, called car, will have the following properties: number of doors, vehicle type and color. We may want a method called printcarddetails () to print these properties
So we got the following class
public class Car { //Attributes private int numberOfDoors; private String colour; private char motorType; //I = ICE, E = Electric F = fuelcell private int carReg; private static int lastCarReg = 1000; //Constructors //Default Constructor public Car() { //Constructor. In this mode, it will give Car some set values numberOfDoors = 4; colour = "Black"; motorType = 'I'; lastCarReg++; //increase the value carReg = lastCarReg; // assign that value to the reg of this Car instance } public Car(int numberOfDoors, String colour, char motorType) { //In this constructor, the user can customize the value of Car this.numberOfDoors = numberOfDoors; this.colour = colour; this.motorType = motorType; lastCarReg++; carReg = lastCarReg; } public Car(int doors) { numberOfDoors = doors; colour = "Black"; motorType = 'I'; } //Getter methods the following are the methods to read various attributes in the Car //get the colour public String getColour() { return colour; } public int getDoors() { return numberOfDoors; } public char getMotorType() { return motorType; } public int getReg() { return carReg; } //Setter Methods the following are the methods to set / change various properties of Car public void setDoors(int num) { numberOfDoors = num; } public void setColour(String col) { if(col.equals("Red") || col.equals("Green")){ colour = col; } } //Functionality other methods public void printCarDetails() { String details = "Number of doors: " + numberOfDoors; details += "\nColour: " + colour; details += "\nMotor Type: " + motorType; details += "Car Reg: " + carReg; System.out.println(details); } public String toString() { String details = "Number of doors: " + numberOfDoors; details += "\nColour: " + colour; details += "\nMotor Type: " + motorType; details += "Car Reg: " + carReg; return details; } /* public Car(int numberOfDoors, String colour,char motorType) { this.numberOfDoors = numberOfDoors; this.colour = colour; this.motorType = motorType; } public void setColour(String colour) { this.colour = colour; } */ }
Note: there is no main method in our class. In the main() method (in another file), we can create the object of Car class like the object of Scanner class
For example:
public class TestCar{ public static void main(String args[]){ //Create a Car instance by calling the default constructor //Here is the Car created with the default value. See the corresponding part of the Car class above Car c1 = new Car(); //Create another Car instance by calling our general constructor with 3 parameters //Here, a custom value is used to create a Car Car c2 = new Car(5,"red",'E'); Car c3 = new Car(16); //The following is the use of various methods, which can be seen by comparing with the Car class mentioned above //Call printCarDetails method on each car c1.printCarDetails(); c2.printCarDetails(); c3.printCarDetails(); System.out.println("Colours:"); System.out.println("The colour of Car C1 : " + c1.getColour()); System.out.println("The colour of Car C2 : " + c2.getColour()); System.out.println("The colour of Car C3 : " + c3.getColour()); c1.setColour("Green"); c3.setDoors(4); c1.printCarDetails(); c3.printCarDetails(); System.out.println(c1.toString()); } }
[naming convention of classes and objects]
1. When creating a class, the class name should always start with an uppercase letter
2. When creating an object of a class, the object name should always start with a lowercase letter, and any subsequent words should start with an uppercase letter
[summary]
The key is to accept the idea that "class is a template". In this template:
We can define the attributes of a kind of things, such as Human height, weight, gender and so on
We can operate these attributes, that is, there are methods. For example, if a person loses weight and we want to change the attribute value of his weight, we can define a "change weight" method to use
We can give the things generated by this template to other parts. For example, I have a method of driving a vehicle, CarDriver, which needs to input a Human type parameter as the driver
Then we can give an object generated by Human to the method
Composition of classes
[array of objects]
Continuing with the previous example, we now want to create multiple cars in our program
One and two are OK. If we want to create multiple car s, it will be very complicated and chaotic to instantiate them respectively one time, so we have array objects
Using arrays to store objects of the same type helps simplify operations
As we said earlier, we can treat a class as a property that stores values -- just as we use int, double, etc., so the use of array objects is the same as the use of arrays before
Again, previously, our int, double, etc. are also types. They are the default types in Java, and they can be stored in arrays
Then our user-defined class is also a "class". Of course, the objects instantiated by it can also be stored in an array
Car CarShouRoom [] = new Car [5] for(int i = 0 ;i < 5 ; i++){ CarShouRoom [i] = new Car(); }
We mentioned six parts of the class before. Let's talk about several parts in detail below:
[Constructors]
A constructor is a special type of method that is called when the new keyword is used with an object
They have no return type (not even void) and must have the same name as the class
Typically, we have a default constructor (usually without parameters) and at least one other constructor with one or more parameters
Let's review Car:
This is the default constructor. In this constructor, we usually preset various values
public Car() { numberOfDoors = 4; colour = "Black"; motorType = 'I'; lastCarReg++; //increase the value carReg = lastCarReg; // assign that value to the reg of this Car instance }
This is a constructor with parameters. When the user writes the corresponding parameters, the user-defined object will be created
public Car(int numberOfDoors, String colour, char motorType) { //We'll discuss this in detail later this.numberOfDoors = numberOfDoors; this.colour = colour; this.motorType = motorType; lastCarReg++; carReg = lastCarReg; }
[Accessor and Mutator Methods]
Accessor accessor methods are used to return (get) property values. They are also called getter methods
The changers Mutator methods are used to change (set) property values, also known as setter methods
The Accessor and Mutator methods provide users with a way to accurately interact with the data in the class
The accessor is responsible for allowing the user to get the corresponding value, and the modifier is responsible for setting and modifying the value
Still take Car as an example. The color of our Car can be obtained by the following method:
public String getColour() { return colour; }
Note that the access method has zero input parameters and has a return type. After all, the accessor is used to obtain the corresponding data, and there must be a return value
Since the method is public, any class can call it
Let's take a look at an example of the changer Mutator, which will change the color of the car:
public void setColour(String carColour) { colour = carColour; }
In contrast to an Accessor, the Mutator method takes one or more parameters and always has a void return type. Because its responsibility is to modify, it needs to accept the modified value, but does not return the value
In essence, they are both methods existing in Class. Through their use, they are divided into two concepts - in essence, they are still methods, and there is nothing special
Naming convention for Accessor and Mutator methods:
The accepted convention is that the first word of the method name starts with a lowercase * * (and will be get or set), while all other words start with uppercase**
such as
For Accessor: get < name > (); For example, getCarReg()
For Mutator: set < name > (); For example, setMotorType()