java basic programming
An overview of the java language
2. Basic grammar
3. Array
Fourth, object-oriented - on
Five, object-oriented - medium
1. Object-oriented feature 2: Inheritance
2. Rewriting the method
3. Keyword: super
4. The whole process of subclass object instantiation
5. Object-oriented feature three: polymorphism
1. Understanding of polymorphism: it can be understood as multiple forms of a thing
2. What is polymorphism?
Object polymorphism: the reference of the parent class points to the object of the child class (or the object of the child class assigns the reference of the parent class)
Example:
Person p = new Man(); Object obj = new Date();
3. Use of polymorphism: virtual method calls
With the polymorphism of objects, we can only call the methods declared in the parent class at compile time, but at runtime, what we actually execute is the method that the subclass overrides the parent class.
Summary: compile to the left; run to the right.
4. Prerequisites for the use of polymorphism: ①Class inheritance relationship ②Method override
5. Examples of the application of polymorphism:
public void func(Animal animal){//Animal animal = new Dog(); animal.eat(); animal.shout(); }
public void method(Object obj){ }
6. Notes on the use of polymorphism:
Object polymorphism, only for methods, not for properties (see left for compilation and execution)
7. About Up-Transformation and Down-Transformation
[External link image transfer failed, the source site may have anti-leech mechanism, it is recommended to save the image and upload it directly (img-HHtCq4JF-1665413403141)(./img/13.png)]
7.1 Upcasting: Polymorphism
7.2 Downcasting:
-
Why use downcasting:
With the polymorphism of the object, the subclass-specific properties and methods are actually loaded in the memory, but since the variable is declared as the superclass type, at compile time, only the properties and methods declared in the superclass can be called. Subclass-specific properties and methods cannot be called.
How can I call subclass-specific implementations and methods? Use downcasting: use the cast operator.
-
How to achieve down transition? Use caster: ()
-
Notes when using:
- ClassCastException may occur when casting is used
- In order to avoid the exception of ClassCastException when downcasting, we first judge instanceof before downcasting, and once it returns true, we will perform downcasting. If false is returned, no downcast is performed.
-
The use of instanceof:
- a instanceof A: Determines whether object a is an instance of A. If it is, return true; if not, return false.
- If a instanceof A returns true, a instanceof B also returns true. where B is the parent class of A.
- It is required that the class to which A belongs and the class A must be the relationship between the subclass and the superclass, otherwise a compilation error occurs.
- Usage scenario: In order to avoid the exception of ClassCastException during downcasting, we first perform instanceof judgment before downcasting, and once it returns true, downcasting is performed. If false is returned, no downcast is performed.
6. Use of Object class
1. Description of the java.lang.Object class
(1) The Object class is the parent class of all java classes
(2) If the extends keyword is not used in the tired declaration to indicate its parent class, the default parent class is java.lang.Object class
(3) The functions (attributes, methods) in the Object class are universal
Attribute: none
Method: equals()/toString()/getClass()/hashCode()/clone()/finalize()/wait()/notify()/notifyAll()
(4) The Object class only declares a constructor with an empty parameter
2.equals() method
- Use of equals() method
(1) is a method, not an operator
(2) Only applies to reference data types
(3) Definition of equals() in the object class
public boolean equals(Object obj){ return (this == obj); }
Description: equals() and == defined in the Object class have the same function: the comparison is whether the address values of the two objects are equal, that is, whether they refer to the same object entity
(4)String, Date, File, wrapper classes, etc. all override the equals() method in the Object class.
After rewriting, the comparison is not whether the address values of the two references are the same, but whether the "entity content" of the two objects is the same.
(5) Usually, if a custom class uses equals(), it is to compare whether the "entity content" of two objects is the same, and you need to rewrite equals() in the object class.
Rewritten rules: Compare whether the entity content of two objects is the same.
-
How to override the equals() method
-
Automatically generated in development
-
Manual rewrite
class User{ String name; int age; //Override equals() public boolean equals(Object obj){ if(obj == this){ return true; } if(obj instanceof User){ User u = (User)obj; return this.age == u.age && this.name.equals(u.name); } return false; } }
-
-
Review the use of the == operator
==: operator
(1.) Can be used in basic data type and reference data type variables
(2.) If the basic data type variables are compared, the comparison is whether the values stored in the two variables are equal (the types are not necessarily the same)
If the comparison is a reference data type variable, the comparison is whether the address values of the two objects are equal, that is, whether they refer to the same object entity
(3) Supplement: When the == symbol is used, it must be ensured that the variable types on the left and right sides of the symbol are the same.
3.toString() method
- Use of toString() method
(1) When we output a reference to an object, we actually call toString() of the current object [premise: cannot be empty]
@Test public void test() { String s = "abc"; s = null; System.out.println(s);//null System.out.println(s.toString());//A NullPointerException occurs }
(2) Definition of toString() in Object class
Public String toString(){ return getClass().getName() + "@" + Integer.toHexString(hashCode()); }
(3) String, Date, File, wrapper classes, etc. all rewrite the toString() method in the Object class. So that when the object's toString() is called, the "entity content" information is returned.
(4) Custom classes can also override the toString() method. When this method is called, the "entity content" of the object is returned
- Override of toString() method: automatic implementation
7. Unit testing method
step:
1. Select the current project - right click: build path -add libraries - JUnit4 - next step
2. Create a java class for unit testing
The java class requirements at this time: ① This class is public ② This class provides a public lunch constructor
3. Declare unit test methods in this class
The unit test method of this class, the permission of the method is public, there is no return value, and there is no formal parameter
4. This unit test method needs to declare the annotation: @Test, and import import org.junit.Test in the unit test class;
5. After declaring the unit test method, you can test the relevant code in the method body
6. After writing the code, left-click on the unit test method name, right-click: run as - JUnit Tesy
illustrate:
1. If executed without any exception: green bar
2. If there is an exception in the execution: red bar
8, the use of packaging
1. In order to make the variables of the basic data type have the characteristics of a class, a wrapper class is introduced.
2. Basic data types and corresponding wrapper classes:
[External link image transfer failed, the source site may have an anti-leech mechanism, it is recommended to save the image and upload it directly (img-slvhoRiC-1665413403142)(./img/14.png)]
3. Conversion between basic data types, wrapper classes, and String
Basic data types <-------> wrapper classes: auto-unboxing and auto-boxing
Basic data types, wrapper classes --------> String: call the overloaded valueOf(Xxx xxx) of String
String-------> basic data type, wrapper class: call parseXxx(String s) of the wrapper class
Note: During conversion, NumberFormatException may be reported
4. Examples of application scenarios
(1) Regarding adding elements in the Vector class, only the method whose formal parameter is Object type is defined.
package com.xiaoli.exer; import java.util.Iterator; import java.util.Scanner; import java.util.Vector; public class ScoreTest { public static void main(String[] args) { //1. Instantiate Scanner for getting student grades from keyboard Scanner scan = new Scanner(System.in); //2. Create a Vector object, Vector v = new Vector(); equivalent to the original array Vector v = new Vector(); //3. Add an array to the Vector by for (;;) or while (true) int maxScore = 0; for (;;) { System.out.println("Please enter grade (1-100 negative number ends)"); int score = scan.nextInt(); if (score < 0) { break; } if (score > 100) { System.out.println("please enter again"); continue; } //3.1 Add operation: v.addElement(Object obj); v.addElement(score);//autoboxing //4. Get the maximum value of student grades if(maxScore < score) { maxScore = score; } } //5. Traverse the Vector, get the grade of each student, and compare it with the maximum grade to get the grade of each student. char level; for (int i = 0;i < v.size();i++) { Object obj = v.elementAt(i); int score = (int)obj; if (maxScore - score <= 10) { level = 'A'; }else if(maxScore - score <= 20){ level = 'B'; }else if(maxScore - score <= 30){ level = 'C'; }else { level = 'D'; } System.out.println("student" + i + " score is" + score +",level is" + level); } } }
Six, object-oriented - next
1. Keyword: static
1.static: static
2.static can be used to modify: properties, methods, code blocks, inner classes
3. Use static to modify properties: static variables
(1) Attributes: According to whether to use static modification, it is divided into: static attributes vs non-static attributes (instance variables)
Instance variables: (not modified by static) We create multiple objects of the class, each of which has an independent set of non-static properties in the class. Modifying a non-static property in one of the objects does not cause the same property value to change in the other objects.
Static variables: (modified by static) We create multiple objects of the class, and multiple objects share a static variable. When modifying a non-static property in one of the objects causes other objects to call this static variable, it is modified.
public class StaticTest { public static void main(String[] args) { Chinese c1 = new Chinese(); c1.name = "Yao Ming"; c1.age = 42; c1.nation = "CHN"; Chinese c2 = new Chinese(); c2.name = "Malone"; c2.age = 34; c2.nation = "China"; System.out.println(c1.nation);//china } } class Chinese{ String name; int age; static String nation; }
(2) Other descriptions of static modified attributes:
①Static variables are loaded with the loading of the class, and can be called by means of "class.static variable".
public static void main(String[] args) { Chinese.nation = "China"; } class Chinese{ static String nation; }
② The loading of static variables is earlier than the creation of objects.
③ Since the class will only be loaded once, there will only be one copy of the static variable in the memory, which will be stored in the static domain of the method area.
④
class variable | instance variable | |
---|---|---|
kind | yes (same life cycle) | no (instance variables are owned by concrete objects and cannot be called through classes) |
object | yes (static variables are loaded before object creation) | yes (born at the same time) |
(3) Examples of static properties: System.out;Math.PI;
4. Use static modification method: static method
(1) It is loaded with the loading of the class, and can be called by means of "class.static method".
(2)
static method | non-static method | |
---|---|---|
kind | yes | no |
object | yes | yes |
(3) In static methods, only static methods or properties can be called
In a non-static method, both static methods or properties can be called, and non-static methods or properties can also be called.
5. Note: In a static method, the this keyword and super keyword cannot be used
class Chinese{ String name; int age; static String nation; public void eat() { System.out.println("Chinese people eat Chinese food"); } public static void walk() { } public static void show() { System.out.println("I'm a Chinese"); //Cannot call non-static structs // eat(); // name = "Tom"; //Can call static structures System.out.println(nation);//Omit Chinese. System.out.println(Chinese.nation); walk(); } }
6. In development, how to determine whether a property should be declared static?
-
Properties can be shared by multiple objects and will not vary from object to object.
-
Constants in classes are also often declared static.
In development, how to determine whether a method should be declared static?
-
Method for manipulating static properties, usually set to static
-
The method in the tool class is customarily declared as static. For example: Math, Arrays, Collections