Classes
What is a class? It can be simply understood as category, type and chestnut: everyone is human, that is, human, here is a category, everyone has many common characteristics (attributes), behavior (methods).
Features are that everyone has names, age, gender and so on, that is, attributes in the class.
Behavior is eating, sleeping (sleep only), drinking water and these things, which are also the methods in class.
Let's see what the class looks like first.
public class People { }
Well, in the long run, class means this is a class. Class is a class in programming, but it doesn't mean class. The public preceding the class is his modifier, indicating that the class is common. The People after the class defines the class name by itself. Note here that, in general, the first letter of the class name is uppercase. The curly brackets after the class name are used to place things inside the class, that is, attributes and methods.
1.1 Member Variables
Member variables are the attributes mentioned above, let's not say more, look at the code:
// Human beings public class People { // Full name private String name; // Age private int age; // Gender private String sex; }
Let's define a human being and give it three attributes: name, age and gender.
Private is also a modifier, representing private; Let's talk later about what the public and private sectors do.
private is followed by a data type, which represents what type of storage this attribute will use. Needless to say, names must be stored in strings, age must be reshaped, gender can be used in strings or characters, but you can also use numbers.
1.2 Membership Method
The member method is the method mentioned above, representing the behavior of a class.
This is the structure:
Modifier Return Type Method Name(Formal parameters(Formal parameters)){ Sentence; }
The curly brackets are the body of the method.
The sample code is as follows:
// Human beings public class People { // Full name private String name; // Age private int age; // Gender private String sex; // This class is the generated shortcut key Alt + insert and then toString() // The purpose of this method is to return the properties of this class as a string @Override public String toString() { return "People{" + "name='" + name + '\'' + ", age=" + age + ", sex='" + sex + '\'' + '}'; } // Sleep public void sleep(){ System.out.println(name + "Be sleeping! And who? That's not very clear."); } }
Let's look at this sleeping method. It prints a string of strings and the void used here for the return type means that there is no return type and no return is required.
If the return type is String, a String value needs to be returned, as does other types.
1.3 Construction Method
The construction method is a method with the same name as the class. The creation of objects is accomplished by the construction method, which is divided into parametric and nonparametric methods. The difference is whether there are parameters or not.
When no constructor is defined in the class, a parameterless constructor is generated by default.
// Human beings public class People { // Full name private String name; // Age private int age; // Gender private String sex; // Parameterless construction method People(){ } // Parametric construction method People(String name, int age, String sex){ this.name = name; this.age = age; this.sex = sex; } }
1.4 Method overload
Generally speaking, method names cannot be duplicated in the same class, but there are special cases, that is, method overload, and method overload is only when method names are the same and parameters are different (can be different types or different numbers of parameters).
In fact, the parameterized and parameterized constructors just now are method overloads, because the number of parameters is different and the method names are the same, so the conditions for method overload are met.
The number of parameters is the same and the types of parameters are different:
public void sleep(String name){ System.out.println(name + "Be sleeping! And who? That's not very clear."); } public void sleep(int age){ System.out.println("General person" + age + "Start sleeping that way?"); }
The number of parameters is different:
public void sleep(String name){ System.out.println(name + "Be sleeping! And who? That's not very clear."); } public void sleep(String name, int age){ System.out.println("General person" + age + "Start sleeping that way?"); }
1.5 static
Statics can be used to modify variables, constants, and methods. static members are classes, but not objects, and classes can be called, but objects cannot. The syntax format of the call is: class name. static class member.
public class People{ // Defining static constants in classes final static int age = 21; // Defining static variables in classes static String name; public static void eat() { System.out.println("eat..."); } public static void main(String[] args) { // Call static constants System.out.println(People.age); // Invoke static variable System.out.println(People.name); // Call static methods People.eat(); } }
1.6 Permission Modifier
Permission modifiers in Java are private, public, and protected, which control access to class and class member variables and member methods.
Yes, to mention more, the default is private if the limit modifier is not weighted in front of the member variable.
1.7 Objects
This object is not your dream object, but what java instantiates with a class is an object, or a variable defined with a class is an object.
1.7.1 Object Creation
Use the new operator to invoke the construction method to create the object:
People people = new People();
1.7.2 Accessing object properties and behavior
When you have, uh, no, when you create an object, you can use Object.Class Members to get the properties and behavior of the object:
// Human beings public class People { // Full name public String name; // Age private int age; // Gender private String sex; // Parameterless construction method People(){ } // Parametric construction method People(String name, int age, String sex){ this.name = name; this.age = age; this.sex = sex; } // This class is the generated shortcut key Alt + insert and then toString() // The purpose of this method is to return the properties of this class as a string @Override public String toString() { return "People{" + "name='" + name + '\'' + ", age=" + age + ", sex='" + sex + '\'' + '}'; } public void sleep(){ System.out.println(name + "Be sleeping! And who? That's not very clear."); } public static void main(String[] args) { // Instantiates an object and initializes its properties with a parametric constructor People people = new People("Zhang San", 21, "male"); // Print the returned string System.out.println(people.toString()); // Call sleep method people.sleep(); // Change the name of the object people.name = "Extrajudicial Maniacs"; // Print the name of the changed object System.out.println(people.name); } }
Console Output:
People{name='Zhang San', age=21, sex='male'} Zhang San is sleeping! And who? That's not very clear. Extrajudicial Maniacs
2. Packaging
In object-oriented programming methods, encapsulation refers to a method of encapsulating and hiding the implementation details of abstract function interfaces.
Encapsulation can be thought of as a protective barrier against random access of the class's code and data to code defined by an external class.
Some of the advantages of packaging:
- Good packaging reduces coupling.
- The structure inside the class can be modified freely.
- You can control member variables more accurately.
- Hide information to achieve details.
The code is as follows:
public class People { // Make properties private so that external access and settings are not directly available // Full name private String name; // Age private int age; // Gender private String sex; // Only by way of acquisition and setup // Get Name public String getName() { return name; } // Set Name public void setName(String name) { this.name = name; } // Getting Age public int getAge() { return age; } // Set Age public void setAge(int age) { this.age = age; } // Get Sex public String getSex() { return sex; } // Set Sex public void setSex(String sex) { this.sex = sex; } }
3. Inheritance
Inheritance is java A cornerstone of object-oriented programming because it allows the creation of hierarchical classes.
3.1 Inheritance keywords
Inheritance can be used extends and implements These two keywords implement inheritance, and all classes inherit from java.lang.Object,Default inheritance when a class does not inherit two keywords object Class.
3.1.1 extends
Inheritance is achieved using the extends keyword, followed by the parent class name (base class), which class it inherits from, whereas this class with extends itself is called a subclass (derived class).
And class inheritance is a single inheritance, that is, a subclass can only have a parent class, so extends can inherit only one class.
Parent Class:
public class People { // Full name private String name; // Age private int age; // Gender private String sex; }
Subclass:
public class Man extends People { }
3.1.2 super and this
super is used to access members of the parent class.
this is used to access its members.
Parent Class:
public class People { // Full name private String name; // Age private int age; // Gender private String sex; public void eat(){ System.out.println("People: eat..."); } }
Subclass:
public class Man extends People { public void eat(){ System.out.println("Man: eat..."); } public void eatTest(){ // eat method of parent class super.eat(); // Your own eat method this.eat(); } }
Test class:
public class Test { public static void main(String[] args) { Man man = new Man(); man.eatTest(); } }
Console Output:
People: eat... Man: eat...
3.1.3 final
final Keyword declaration classes can define classes as final classes that cannot be inherited. Or it can be used to decorate a method that cannot be overridden by subclasses. Instance variables can also be defined as final,Defined as final The variable of cannot be modified.
It looks like a sterilization operation, good fellow, future generations are not allowed. I seem to hear cries from finals and finals.
Real variables are good, but they become constants. Except when they are defined, they can't be modified later, at least better than sterilization.
Just kidding, each has its own good and bad.
Declare class:
Permission modifier final Class name{}
Declare method:
Permission modifier final Return type method name(){}
Declare constants:
Permission modifier final Data type variable name;
4. Polymorphism
stay Java In general, overloading and overriding methods are used to implement class polymorphisms. The same event occurs on different objects with different results.
There are three prerequisites for polymorphism:
- inherit
- Rewrite
- Parent p = new Child();
4.1 Rewrite
Simply put, if the method name of the subclass is the same as the method name of the parent class, then the subclass cannot inherit the method of the parent class. The method called the subclass overrides the method of the parent class, which can also be understood as overwriting.
Parent (human):
public class People { // Full name private String name; // Age private int age; // Gender private String sex; public void eat(){ System.out.println("People: eat..."); } }
Subcategory (male):
public class Man extends People { @Override public void eat(){ System.out.println("Man: eat..."); } }
Subcategory (females):
public class Woman extends People { @Override public void eat(){ System.out.println("Woman: eat..."); } }
Test class:
public class Test { public static void main(String[] args) { People people1 = new Man(); People people2 = new Woman(); people1.eat(); people2.eat(); } }
Console Output:
Man: eat... Woman: eat...
5. Interfaces
Interfaces are not classes, but they are very similar. But interfaces can't be instantiated, and they don't have objects. Unfortunately, like me, they don't have objects.
Also, the method cannot be implemented, that is, the method body parameter cannot be followed directly by a semicolon, just like the C++ function prototype.
Although an interface cannot instantiate an object, it can be implemented by a class, and the class that implements it must implement all of its methods, none of them. If you dare less, he dares to give you an error. It is very annoying and feels more like a specification and constraint.
Declaration of 5.1 Interface
Come on, let's see how the interface says:
interface People { public void eat(); public void sleep(); }
In this way, the keyword of the interface is interface.
Implementation of 5.2 Interface
As mentioned earlier, to implement an interface, all his methods must be implemented.
Classes use the implements keyword to implement interfaces, which cannot be said to be similar to the use of inherited keywords, but only a hair.
The code is as follows:
public class Man implements People { public void eat(){ System.out.println("Man: eat...") } public void sleep(){ System.out.println("Man: sleep...") } }
Inheritance of 5.3 interface
Classes cannot inherit interfaces, but interfaces can inherit interfaces and use the extends keyword.
Parent interface:
public interface People { public void eat(); public void sleep(); }
Subinterface:
public interface Man extends People{ public void work(); }
If the class implements the People interface, only two methods need to be implemented, and if the Man interface is implemented, three methods need to be implemented.
Multiple Inheritance of 5.4 Interface
Classes can't inherit much, but interfaces can, well, be double-labeled.
Format:
Permission modifier interface Subinterface extends Parent Interface 1, Parent Interface 2{}
6. Abstract Classes
In addition to the fact that abstract classes cannot instantiate objects, other functions of the class still exist, and member variables, member methods, and construction methods are accessed in the same way as regular classes.
Click, other classes have objects, you don't.
Since abstract classes cannot instantiate objects, abstract classes must be inherited to be used, similar to interfaces.
6.1 Define abstract classes
An abstract class is defined by an abstract class:
public abstract class People { // Full name private String name; // Age private int age; // Gender private String sex; public void eat(){ System.out.println("People: eat..."); } public void sleep(){ System.out.println(name + "Be sleeping! And who? That's not very clear."); } // Get Name public String getName() { return name; } // Set Name public void setName(String name) { this.name = name; } // Getting Age public int getAge() { return age; } // Set Age public void setAge(int age) { this.age = age; } // Get Sex public String getSex() { return sex; } // Set Sex public void setSex(String sex) { this.sex = sex; } // //parameterless construction method People(){ } // Parametric construction method People(String name, int age, String sex){ this.name = name; this.age = age; this.sex = sex; } // The purpose of this method is to return the properties of this class as a string @Override public String toString() { return "People{" + "name='" + name + '\'' + ", age=" + age + ", sex='" + sex + '\'' + '}'; } }
Although he has constructors, he has all the ordinary classes. Unfortunately, it is impossible to instantiate them. You can try them.
6.2 Inheriting abstract classes
The inheritance of an abstract class is the same as that of an ordinary class, with the following code:
public class Man extends People { private String address; Man(String name, int age, String sex, String address){ super(name, age, sex); this.address = address; } @Override public void eat(){ System.out.println("Man: eat..."); } }
6.3 Abstract Methods
The concrete implementation of an abstract method is determined by its subclasses, which you can declare as abstract in the parent class.
Declare with the abstract keyword that an abstract method contains only one method name, not a method body.
As long as there is only one abstract method in a class, this must be an abstract class.
Parent Class:
public abstract class People { // Full name private String name; // Age private int age; // Gender private String sex; public abstract void eat(); }
Subclass:
public class Man extends People { private String address; public void eat(){ System.out.println("Man: eat..."); } }
7. Exception handling
Adding exception handling to places where exceptions may occur improves the robustness and security of your code.
There are three types of exceptions:
- Checkable exceptions: The most representative of checkable exceptions is exceptions caused by user errors or problems that programmers cannot foresee. For example, when you open a file that does not exist, an exception occurs that cannot be simply ignored at compile time.
- Runtime exceptions: Runtime exceptions are exceptions that may be avoided by programmers. Contrary to checkable exceptions, runtime exceptions can be ignored at compile time.
- Error: Error is not an exception, but a problem that is out of the programmer's control. Errors are often ignored in code. For example, when a stack overflows, an error occurs that cannot be checked at compilation.
7.1 Catch Exceptions
Catching exceptions uses the try and catch keywords in the following format:
try { }catch(ExceptionName e) { }
7.2 Multiple capture blocks
The case where a try block is followed by more than one catch block is called multiple capture in the following format:
try{ }catch(Exception Type 1 Variable Name 1){ }catch(Exception Type 2 Variable Name 2){ }catch(Exception Type 3 Variable Name 3){ }
7.3 finally
The final keyword is used to create a code block that is executed after the try code block.
The code in the finally block of code is always executed regardless of whether an exception occurs or not.
The format is as follows:
try{ }catch(Exception Type 1 Variable Name 1){ }finally{ }