1. Object oriented
All objective things are objects, and all things are objects.
1.1 objects include characteristics and behaviors.
Characteristics: it is called attribute, generally a noun, which represents what the object has.
Behavior: it is called method, which is generally a verb and represents what the object can do.
1.2 what are classes? (see the figure below)
1.3 definition of class:
public class Dog{ String breed;//varieties int age;//Age String sex;//Gender String furColor;//Hair color public void eat(){ System.out.println("eating..."); }//A way to eat }
Definition of properties and methods:
Attribute: represented by variable, also known as instance variable
Syntax: data type attribute name;
Location: inside the class, outside the method.
Method: represented by method, also known as instance method.
Syntax:
public return value type method name (formal parameter){
//Main body of method
}
1.4 object creation
public class TestCreateObject{ public static void main(String[] args){ Dog myDog=new Dog();//Creating objects based on Dog classes myDog.breed="Bulldog"; myDog.age=2; myDog.sex="common"; myDog.furColor="black and white";//Access properties and assign values myDog.eat(); myDog.sleep();//Access method } }
1.5 relationship between class and object
Class: defines the characteristics and behaviors that an object should have. Class is the template of an object
Object: an entity with multiple features and behaviors. An object is an instance of a class
1.6 differences between instance variables and local variables
1.7 overloading of methods
You can have the same method name in the class, but the parameter list and parameter types of these methods are different. Methods constructed in this way are called method overloading.
1.8 construction method
Construction method is an important method of class.
When instantiating an object, the first call is the class constructor, and the class constructor must be called to create the object.
Creation method of construction method:
public class Dog{ int age; public Dog(){ }//Default constructor. This constructor can be omitted and will be added by default public Dog(int age){ this.age=age;//This keyword is used here to represent this object. }//This is a construction method with parameters. You need to create and call it yourself }
Syntax of construction method:
The name as like as two peas (public) (parameter list) {
Method body;
}
Problems encountered in learning:
1. Defines a student class and creates an object array of the student class, such as:
A null pointer error occurred during the execution of the above code. Solution: the assignment method should be changed to:Student[] stu=new Student[5];// Then assign a value to him stu[0].name="Zhang San";//There is a name attribute in the student class
Error reason: student[] stu=new Student[5]; Mistakenly think that the creation of this array is to create an array with five objects. In fact, it only opened up five spaces in the heap for storing student objects, and did not create objects# 2. Three characteristics: encapsulation, inheritance and polymorphismStudent stu1=new Strudent();//Create an object stu1.name="Zhang San";//Assign values to object properties stu[0]=stu1;//Then assign this object to the array
2.1 packaging
2.1.1 necessity of packaging:
2.1.2 what is encapsulation
Set the access rights of the attributes in the class to private attributes, provide a public access modification method, and write the necessary control statements in the method to make the value of the attribute within the range we need.
Example:
class Student{ private String name; private int age; public void setName(String name){ this.name=name; } public String getName(){ return this.name; } public void setAge(int age){ if(age<0||age>100){//The age of a student can not be less than zero, and the limit can not exceed 100 years old System.out.println("Invalid age, assignment failed"); }else{ this.age=age; } } public int getAge(){ return this.age; } }
2.2 succession
2.2.1 inheritance in procedures
Inheritance in program is a gift or acquisition of characteristics and behaviors between classes
The inheritance relationship between two classes must meet the relationship of "is a".
As shown in the figure:
2.2.2 inherited syntax
Syntax: calss subclass extends parent class {} / / defines that the subclass is and displays the inherited parent class
Application: after the inheritance relationship is generated, the subclass can use the properties and methods of the parent class, or define the methods and properties unique to the subclass
Benefits: it can not only improve the reusability of code, but also improve the scalability of code
2.2.3 characteristics of inheritance
java inheritance is single inheritance, but it can be inherited at multiple levels. For example, the parent class also inherits its parent class, and the employment of the child class is equivalent to inheriting the grandparent class. However, private methods and properties are not inheritable
2.2.4 method rewriting
When the parent class has a method, but the subclass does not apply, but needs this behavior, the subclass can write the same method, but the method body is different, this is rewriting.
#2.3 polymorphism
2.3.1 interpretation of polymorphism:
One thing may have different effects in the eyes of different people, which is the display of polymorphism.
2.3.2 the implementation method in the program is:
First declare a parent class, which has a method.
Then declare multiple subclasses to inherit the parent class and override the method.
When calling, point to the subclass object with the parent class declaration, and then call this method with this declaration to realize different functions.
2.3.3 unpacking and packing
Packing (upward transformation)
In fact, the parent class reference to the child class object is a boxing process.
At this time, this reference can only call the methods and properties of the parent class. Sometimes when we need to call the method properties unique to the child class, we can't call it directly. At this time, we need to unpack
Unpacking (downward transformation)
Parent class references are forced to be converted to child class references.
However, the object referred to by this parent class reference must be the object of this subclass, otherwise an error will be reported (the method to avoid is to detect first, and the detection method is the keyword instanceof). At this time, this reference can call not only the unique properties and methods of the subclass, but also the properties and methods of the parent class.
Stress: at this time, the parent class reference and child class reference point to the same object, and the data obtained from one change will also change.
3. Three modifiers
Abstract, static, final
3.1 abstraction
3.1.1 what is abstraction
Specious, but not; Having the characteristics of an object, but incomplete.
In a program, if this class is an abstract class, then this class cannot be created as an object
3.1.2 creation of abstract classes
3.1.3 functions of abstract classes
Abstract methods can only be written in abstract classes. Abstract classes do not necessarily have abstract methods.
If an abstract class is inherited, all abstract methods of the abstract class must be overridden by subclasses. If the subclass is also an abstract class, the subclass can override methods or skip them. However, if a non Abstract subclass is encountered, all abstract methods not overridden by the parent must be overridden.
3.2. Static attributes
3.2.1 comparison between instance attribute and static attribute
3.2.2 what is static
Concept:
static can modify properties and methods.
They are called static attributes (class attributes) and static methods (class methods).
Static members are members shared by all objects of the class.
There is only one copy in the whole class, and multiple copies will not be generated due to the creation of multiple objects.
You do not have to create an object, but you can access it directly through the class name.
Static method is to add static before the return value type of ordinary method
Static methods and static attributes can be called directly using class name point attributes or methods. You don't have to create objects.
3.3 final
3.3.1 what is final
Concept: final and unchangeable.
final modifiable content:
Class (final class)
Method (final method)
Variable (final variable)
final modifier class: this class cannot be inherited.
String, Math and System are all final modified classes and cannot be inherited.
final modifier method: this method cannot be overridden.
It means the final method. Subclass modification in the form of override is not supported
4. Interface
4.1 basic use
Concept: an interface is equivalent to a special abstract class, and its definition method and components are similar to those of an abstract class. Use the interface keyword to define an interface.
characteristic:
- Cannot create object without constructor
- Only static constants and abstract methods can be defined.
Case demonstration: Custom Interface
public interface MyInterface{ String NAME="Interface 1"; //This writing method is omitted and compiled as: //public static final String NAME = "interface 1"; void method(); //The method is actually compiled as: //public abstract void method1(); }
Implementation class:
public class Impl implements MyInterface{ @override //This means rewriting public void method(){ System.out.println("method"); } //Write this method as the output method }
Test class
public class TestInterface{ public static void main(String[] args){ MyInterface myInterface=new Impl(); myInterface.method(); } }
4.2 differences between and abstract classes
Similarities:
Can be compiled into bytecode files.
Cannot create object.
Can be used as a reference type.
It has the methods defined in the Object class.
difference:
All attributes are public static constants, which are implicitly decorated with public static final.
All methods are public abstract methods, which are implicitly decorated with public abstract.
No constructor, dynamic code block, static code block.
4.3 understanding of interfaces
At the micro level, interface is a kind of capability and convention
Definition of interface: it represents a certain capability.
Definition of method: specific requirements of ability.
For example, I create an interface called magic
There is a method called spell attack in the interface
Then write a class to realize magic, which is called fireball
Class rewrites the method of spell attack: fireball causes spell damage by concentrating the enemy.
Then write a call class, which uses the interface to create a reference named Angela, and then create a fireball object. Angela's reference points to the fireball object, and then uses Angela to point magic attacks. Then, it completes the process of creating, implementing and calling the interface that Angela uses the fireball to cause magic attacks on the enemy.
Why not use abstract classes instead of interfaces?
A: first of all, why use abstract classes or interfaces? It should be that magic is the ability of many heroes. Those magic heroes can show the ability of these mages as long as they implement interfaces or inherit abstract class rewriting methods, which reduces redundant code. Then why use interfaces instead of classes? Not all heroes have spells. Classes generally store properties and methods common to all subclasses, so choose interfaces.
4.4 from a macro perspective, the interface is a standard and a specification
For example, I create an interface named USB
There is a method called working.
Then I designed a computer class, which has three USB interface properties,
Then three classes are designed to realize the USB interface, such as USB flash disk, USB electric fan and USB keyboard.
Then create USB flash disk and other objects in the computer class. Then assign these objects to the three USB interface attributes of the computer (this can be regarded as I insert the USB disk into the USB interface of the computer). Then work with USB to complete the working mode of USB disk and other objects.
From this example, it can be seen that the interface is a standard and a specification. If my computer attribute uses not the USB interface but the type-c interface, then my USB disk and other objects that use the USB interface cannot be used by the computer, or the USB disk and other objects do not use the USB interface. Similarly, the computer cannot use the functions of USB disk and other objects.
Example code display:
usb interface:
public interface Usb{ void work(); }
Computer
public class Computer{ private Usb usb1; private Usb usb2; private Usb usb3; public void open() { System.out.println("The computer is on"); if(usb1!=null) { usb1.work(); } if(usb2!=null) { usb2.work(); } if(usb3!=null) { usb3.work(); } } public Usb getUsb1() { return usb1; } public void setUsb1(Usb usb1) { this.usb1 = usb1; } public Usb getUsb2() { return usb2; } public void setUsb2(Usb usb2) { this.usb2 = usb2; } public Usb getUsb3() { return usb3; } public void setUsb3(Usb usb3) { this.usb3 = usb3; } }
usb disk class implements usb interface:
public class Upan implements Usb{ @Override public void work(){ System.out.println("U The disk is connected and can be used U The disk stores files"); } }
usb interface for electric fan:
public class Fan implements Usb{ @Override public void servies() { System.out.println("The fan has been turned on and can cool down"); } }
usb interface for keyboard:
public class KeyBoard implements Usb{ @Override public void servies() { System.out.println("The keyboard is connected and can be used to type"); } }
Test class (using the interface to the computer and calling the implementation interface class):
public class GameUser { public static void main(String[] args) { Computer cp=new Computer(); //First create a computer object. The computer is the user of the interface cp.open(); //After boot, there is no object access to any usb interface Upan m=new Upan(); //Create a USB flash disk object. The USB flash disk is the implementer of the interface. The function of the interface depends on the USB flash disk cp.setUsb1(m); //Connect the USB flash disk with the USB 1 interface here Fan f=new Fan(); cp.setUsb2(f); KeyBoard k=new KeyBoard(); cp.setUsb3(k); cp.open(); //After completing the above connection code, turn it on again, there will be three usb interfaces connected, and then there will be different functions. } }
4.5 callback principle
Interface callback: the user of the existing interface, followed by the implementer of the interface.
4.6 benefits of interface:
- The coupling degree of the program is reduced.
- Use polymorphism more naturally.
- Design and implementation are completely separated.
- Easier to build program framework.
- It is easier to replace the specific implementation.
5. Inner class
5.1 classification of internal classes
- Member inner class
- Static inner class
- Local inner class
- Anonymous Inner Class
5.2 what is an internal class
Concept: define a complete class inside a class.
characteristic:
- After compilation, an independent bytecode file can be generated.
- The inner class can directly access the private members of the outer class without breaking the encapsulation.
- It can provide necessary internal functional components for external classes.
5.3 introduction to internal classes
5.3.1 member internal class
As the name suggests, the class written in a class has the same status as the properties and methods. It can call all the properties and methods of the external class. When the external class calls the properties and methods of the internal class, it also needs to create an object to call. At this time, the internal class is the same as the ordinary internal class, and the internal class can also inherit the parent class and implement the interface. This, on the other hand, enables Java to implement the function of multi class inheritance.
5.3.2 static internal class
The class we create in the java file cannot be modified with static, but our inner class can be modified with static, which is called static inner class.
Features of static internal classes:
It does not depend on external class objects, can be created directly or accessed through class names, and can declare static members.
Only static members of external classes can be accessed directly (instance members need to instantiate external class objects).
Case demonstration:
public class Outer { private String name="xxx"; private int age=18; //Static inner class: same as outer class static class Inner{ private String address="Shanghai"; private String phone="111"; //Static member private static int count=1000; public void show() { //What about calling the properties of the external class //1 create an external class object first Outer outer=new Outer(); //2. Call the property of the external class object System.out.println(outer.name); System.out.println(outer.age); //Call the properties and properties of the static inner class System.out.println(address); System.out.println(phone); //Call the static properties of the static inner class System.out.println(Inner.count); } } }
Test class call:
public class TestOuter { public static void main(String[] args) { //Create static inner class objects directly Outer.Inner inner=new Outer.Inner(); //Call the method inner show(); } }
5.3.3 local internal class
Defined in an external class method, the scope of scope and creation object scope are limited to the current method.
When a local internal class accesses a local variable in the current method of an external class, the variable must be modified to final because it cannot guarantee that the life cycle of the variable is the same as itself.
Limit the scope of use of the class.
Case presentation:
public class Outer { private String name="Lau Andy"; private int age=35; public void show(final int i) { //Define local variables String address="Shenzhen"; //Local inner class: note that no access modifier can be added class Inner{ //Properties of local inner classes private String phone="15588888888"; private String email="liudehua@qq.com"; private final static int count=2000; public void show2() { //Accessing properties of an external class System.out.println(Outer.this.name); System.out.println(Outer.this.age); //Accessing properties of an inner class System.out.println(this.phone); System.out.println(this.email); //Accessing local variables, jdk1 7 requirement: the variable must be constant final, jdk1 8 auto add final System.out.println("Shenzhen"); System.out.println(i); } } //Create a local internal class object Inner inner=new Inner(); inner.show2(); } }
Test class:
public class TestOuter { public static void main(String[] args) { Outer outer=new Outer(); outer.show(120); } }
5.3.4 anonymous inner class
Local inner class without class name (all characteristics are the same as local inner class).
You must inherit a parent class or implement an interface.
The syntax combination of defining a class, implementing a class and creating an object can only create one object of this class.
Advantages: reduce the amount of code.
Disadvantages: poor readability.
Case presentation:
Anonymous inner classes are generally used temporarily when they implement this interface and have few opportunities to use it.
Define a test interface:
public interface Usb { //service void service(); }
Use of anonymous inner classes:
public class TestUsb { public static void main(String[] args) { //Use anonymous inner class optimization (equivalent to creating a local inner class) Usb usb=new Usb() { @Override public void service() { System.out.println("The computer is connected successfully and the fan starts to work...."); } }; usb.service(); } }
6. object class
6.1 general
- Superclass, base class, direct or indirect parent class of all classes, located at the top of the inheritance tree.
- Any class that does not write extends to inherit from a class will inherit directly from the Object class by default, otherwise it will inherit indirectly
Yes. - The methods defined in the Object class are the methods that all objects have.
- The Object type can store any Object.
- As a parameter, any object can be accepted.
- As a return value, any object can be returned.
As the parent class of all classes, object has many methods, which we can use
6.2 method introduction
6.2.1 getClass()
public final Class<?> getClass(){...}
Returns the actual object type stored in the reference.
Application: it is usually used to judge whether the actual storage object types in two references are consistent.
6.2.2 hashCode() method
public int hashCode(){...}
Returns the decimal hash code value of the object.
A numeric value of type int calculated by the hash algorithm based on the address or string or number of the object.
The hash code is not unique. It can ensure that the same object returns the same hash code, and try to ensure that different objects return different hash codes.
6.2.3 toString() method
public String toString(){...}
Returns the string representation (representation) of the object.
This method can be overridden according to program requirements, such as displaying the attribute values of the object
6.2.4 equals() method
public boolean equals(Object obj){...}
The default implementation is (this == obj). Compare whether the addresses of two objects are the same.
You can overwrite and compare whether the contents of the two objects are the same.
equals rewrite steps:
Compares whether two references point to the same object.
Determine whether obj is null.
Judge whether the actual object types pointed to by the two references are consistent.
Cast type.
Compare whether the attribute values are the same in turn
equals method override:
public class Student { private String name; private int age; public Student() { } public Student(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Student [name=" + name + ", age=" + age + "]"; } @Override public boolean equals(Object obj) { //1 judge whether two objects are the same reference if(this==obj) { return true; } //2 judge whether obj is null if(obj==null) { return false; } //3. Judge whether it is the same type //intanceof determines whether an object is of a certain type if(obj instanceof Student) { //4 cast type Student s=(Student)obj; //5 familiar if(this.name.equals(s.getName())&&this.age==s.getAge()) { return true; } } return false; }
Test student override method equal class:
public class TestStudent { public static void main(String[] args) { //1getClass method System.out.println("------------1getClass---------"); Student s1=new Student("aaa", 20); Student s2=new Student("bbb",22); //Judge whether s1 and s2 are of the same type Class class1=s1.getClass(); Class class2=s2.getClass(); if(class1==class2) { System.out.println("s1 and s2 Belong to the same type"); }else { System.out.println("s1 and s2 Not of the same type"); }System.out.println("-----------2hashCode------------"); //2hashCode method System.out.println(s1.hashCode()); System.out.println(s2.hashCode()); Student s3=s1; System.out.println(s3.hashCode()); //3toString method System.out.println("-----------3toString------------"); System.out.println(s1.toString()); System.out.println(s2.toString()); //4equals method: judge whether two objects are equal System.out.println("-----------4equals------------"); System.out.println(s1.equals(s2)); Student s4=new Student("Xiao Ming", 17); Student s5=new Student("Xiao Ming",17); System.out.println(s4.equals(s5)); } }
6.2.5 finalize() method
- When the object is determined to be a garbage object, the JVM automatically calls this method to mark the garbage object and enter the collection queue.
- Garbage object: garbage object when there is no valid reference to this object.
- Garbage collection: GC destroys garbage objects to free up data storage space.
- Automatic recycling mechanism: the JVM runs out of memory and recycles all garbage objects at one time.
- Manual recycling mechanism: use system gc(); Notify the JVM to perform garbage collection.