Algorithm website: https://visualgo.net/
Chapter 5 advanced JAVA object-oriented programming
To create a new package, write it upside down according to the domain name to ensure that the package is unique
You can create new classes in the package. The directory tree is shown in the figure below
5.2
5.2.3 = = and equals methods
package com.bjsxt.inherit; import java.util.Objects; public class User extends Object{ int id; String name; String pwd; User(int id,String name,String pwd){ this.id = id; this.name = name; this.pwd = pwd; } public static void main(String[] args){ User u1 = new User(1001,"Zhang San","123456"); User u2 = new User(1001,"Li Si","Zhang San"); System.out.println(u1); System.out.println(u2.toString()); System.out.println(u1 == u2); System.out.println(u1.equals(u2)); } //Here is a rewrite of the equals method in the Object. If the IDs of the two objects are the same after rewriting, it is cons id ered that the two objects are the same //Without rewriting, when using the default equals, two objects are considered to be the same only if their addresses are the same. public boolean equals(Object obj){ if(obj==null){ return false; //Return has two functions: return value and end method operation }else { if(obj instanceof User){ User u1 = (User)obj; if(u1.id == this.id){ return true; } } } return false; } }
When rewriting equals, you can also use the shortcut key ALT+insert to rewrite equals and hashcode in the automatically generated code
In the String class, you can see that equals has also been overridden
5.2.4 super keyword (reading)
5.4.2 realization of packaging
First look at a small problem, 'running the following program will report an error
package cn.sxt.gao7; import cn.sxt.gao6.Person; public class Student { Person p1 = new Person(); public static void main(String[] args){ System.out.println(p1.toString()); } }
The error content is shown in the figure. Analysis: the p1 variable cannot be found because it is not defined in the main function and no address is opened for p1. Although there is p1 in the above, it belongs to the writing method of combination and does not assign an address to p1
The correct writing is
package cn.sxt.gao7; import cn.sxt.gao6.Person; public class Student { public static void main(String[] args){ Person p1 = new Person(); //This is the change System.out.println(p1.toString()); } }
5.9 interface
5.9.1 new features after Java 8
Default methods are allowed in the interface
Java 8 and older versions allow you to add a non abstract method implementation to the interface. You only need to use the default keyword (default here is different from default in the package). This feature is also called the default method (also known as the extension method)
The difference between the default method and the abstract method is that the abstract method must be implemented, and the default method is not. As an alternative, the interface can provide the implementation of the default method, and all the implementation classes of this interface will inherit this method.
Basically not. It may be needed in some open source software
package com.bjsxt.testInterface2; public class Test { public static void main(String[] args){ A a = new Test_A(); a.moren(); } } interface A { default void moren(){ //Note that the default method is different from the abstract method. The default here is different from the default in the package System.out.println("I'm the interface A Default method in!"); } } class Test_A implements A{ @Override public void moren() { System.out.println("I BU Is the interface A Default method in!"); } } }
Static methods are allowed in the interface
After Java 8, we can also directly define the implementation of static methods in the interface. This static method is directly subordinate to the interface (the interface is also a class, a special class) and can be called through the interface name.
If a static method with the same name is defined in a subclass, it is a completely different method, which is directly subordinate to the subclass. It can be called directly through the subclass name.
package com.bjsxt.testInterface2; public class Test { public static void main(String[] args){ // B b = new Test_B (); // This is wrong // b.staticMethod(); Test_B b = new Test_B (); b.staticMethod(); B.staticMethod(); } } interface B{ public static void staticMethod(){ System.out.println("B.staticMethod"); } } class Test_B implements B{ public static void staticMethod(){ System.out.println("Test_B.staticMethod"); } }
Static and default methods
Static methods cannot call default methods
The default method can call static methods
5.10 internal class
How to create an internal class object
How to call the properties of an external class in an internal class
package com.bjsxt.testinertclass; public class Outer1 { private int age =10; private void show(){ System.out.println("You look good"); } //Inner class public class Inner1{ private String name ="time"; private int age =20; public void showInner(){ System.out.println("Inner.showInner"); System.out.println(age); //What is called here is the age variable of the inner class System.out.println(Outer1.this.age); //What is called here is the age attribute of the external class //When it has the same name as an internal class attribute, you can use outer1 this. Called in the same way // System.out.println(Outer1.age); // That's wrong show();//Internal members of an external class can be used directly } } public static void main(String[] args){ Outer1.Inner1 inn01 = new Outer1().new Inner1(); //How to create an internal class 1 inn01.showInner(); Outer1 out02 = new Outer1(); Inner1 inn02 = out02.new Inner1(); //How to create an internal class 2 inn02.showInner(); } }
Use of anonymous inner classes
package com.bjsxt.testinertclass; public class TestAnonymousInnerClass { public void test(A a) { a.run(); } public static void main(String[] args) { TestAnonymousInnerClass tai = new TestAnonymousInnerClass(); // AA aa = new AA(); //tai.test(aa); //He is an anonymous inner class tai.test(new A(){ @Override public void run() { System.out.println("Wo Nen Niang"); } }); } } interface A{ void run(); } //Classes with names can be used repeatedly class AA implements A { @Override public void run() { System.out.println("Nest tender father"); } }
5.11.1 string comparison
==Are the comparison objects the same
equals to compare whether the contents of two string objects are the same
7.1 one dimensional array
All searches need to be reprocessed according to the new rules
When indexing, the header does not include the tail. For example, the element at the position of index 2-6 displays a[2] a[3] a[4] a[5] on the subscript
Arrays.fill(a,2,6,100); //When using array filling or other methods to find java strings with header and no tail, the header and no tail are generally used for indexing //That is, 2 3 4 5 includes 2 but not 6
7.2 two dimensional array
Two dimensional array can be regarded as an array with array as elements, which can be seen from the memory analysis process
Two dimensional arrays are not commonly used in the work. Later, there will be container related methods to replace them
7.3 array printing: arrays ToString (array name)
The following code, why arrays ToString (array name) can be used directly without instantiation
You can hold down the alt key and left click on the Arrays letter to jump to the corresponding source code. You can find that the toString () method is a static method
Static methods can be called directly with classes, which are actually class methods
package com.bjsxt.array; import java.util.Arrays; /** * Practice of two-dimensional array * Use Object [] [] to store the data of the whole table */ public class Test09 { public static void main(String[] args){ //Each one-dimensional array represents a row of data Object[] emp0 = {1001,"Gao Qi",18,"lecturer","2006-2-14"}; Object[] emp1 = {1002,"Gao Xiaoqi",19,"assistant","2007-10-10"}; Object[] emp2 = {1003,"Gao Xiaoqin",20,"headmaster","2008-5-5"}; Object [][] emps = new Object[3][]; emps[0] = emp0; emps[1] = emp1; emps[2] = emp2; //Print System.out.println(Arrays.toString(emps[0])); //Arrays.toString is not instantiated System.out.println(Arrays.toString(emps[1])); System.out.println(Arrays.toString(emps[2])); Test10.print(); } }
8. It is very important to use Java beans and arrays to store table information. It will be used every day later (section 120)
package com.bjsxt.array; public class Test11 { public static void main(String[] args) { //Press crtl+d before a line to copy the changed line to the next line Emp emp0 = new Emp(1001,"High efficiency",18,"programmer","2019-9-9"); Emp emp1 = new Emp(1002,"height J",18,"programmer","2019-9-10"); Emp emp2 = new Emp(1003,"High opposition",18,"programmer","2019-9-11"); // Emp[] emps = {emp0,emp1,emp2}; // initiate static Emp[] emps = new Emp[3]; //dynamic initialization emps[0] = emp0; emps[1] = emp1; emps[2] = emp2; for (int i = 0;i< emps.length;i++) { System.out.println(emps[i].toString()); } } } class Emp { private int id; //Using javabean encapsulation private String name; private int age; private String job; private String hiredate; public int getId() { return id; } public String getName() { return name; } public int getAge() { return age; } public String getJob() { return job; } public String getHiredate() { return hiredate; } public Emp(){} //Generally, it is recommended to have a parameter constructor public Emp(int id, String name, int age, String job, String hiredate) { this.id = id; this.name = name; this.age = age; this.job = job; this.hiredate = hiredate; } @Override public String toString() { //Tab \ t //It's better to use the form of getName, which is convenient to change and the attribute is not convenient to change, but functions such as getName can be changed easily return getId()+"\t"+getName()+"\t"+getAge()+"\t"+getJob()+"\t"+getHiredate(); } }
The output result is
"C:\Program Files\Java\jdk-13.0.2\bin\java.exe" "-javaagent:E:\javasoft\idea2020\IntelliJ IDEA 2020.2.4\lib\idea_rt.jar=52780:E:\javasoft\idea2020\IntelliJ IDEA 2020.2.4\bin" -Dfile.encoding=UTF-8 -classpath C:\Users\gou\IdeaProjects\wang01\out\production\wang01 com.bjsxt.array.Test11
1001 high efficiency 18 programmer September 9, 2019
1002 height J 18 programmer 2019-9-10
1003 high objection 18 programmer 2019-9-11
9 generics
9.2.1 defining generics
Generic characters can be any identifier, generally using several Tags: E,T,K,V,N,?
Generic tag | Corresponding word | explain |
---|---|---|
E | Element | Used in a container to represent elements in the container |
T | Type | Represents a common JAVA class |
K | Key | Represents a Key, for example: Key in Map |
V | Value | Representation value |
N | Number | Indicates the value type |
? | Represents an indeterminate JAVA class |
9.2.1 generic classes
A generic class defines a generic type on a class. When users use the class, they define the type. The specific use method of generic class is to add one or more type parameter declarations after the class name, such as `, < T, K, V >
Grammatical structure
`public class class name < generic notation >{
}`
example
/* Create a Generic class Generic */ public class Generic <T>{ //Here, T is used to represent ordinary generic classes private T flag; public void setFlag(T flag){ this.flag = flag; } public T getFlag(){ return this.flag; } }
/* Test this generic class */ public class Test { public static void main(String[] args) { Generic<String> generic = new Generic<>(); //Generic classes are used here //String is passed, that is, when creating a generic class, you don't need to care about what parameters are passed, and you can consider them when calling. Convenient programming generic.setFlag("admin"); //generic.setFlag(100); There is a compilation error, because it is determined that the class to be transmitted is String class, and int cannot be transmitted any more. String flag = generic.getFlag(); System.out.println(flag); Generic<Integer> generic1 = new Generic<>(); //What is passed here is the wrapper class generic1.setFlag(100); Integer flag1 = generic1.getFlag(); System.out.println(flag1); } }
9.2.2 generic interface
Generic interfaces are consistent with the declarations of generic interfaces and generic classes. The specific types of generic interfaces need to be declared in the implementation class
Syntax structure public interface interface interface name < generic notation > {}
example
/** * Define a generic interface */ public interface Igeneric<T> { T getName(T name); // }
/** * Implement defined generic interfaces * You can find that the original T has become a String * When overriding the getName method, the returned type is also String */ public class IgenericImpl implements Igeneric<String>{ @Override //Press alt+insert and insert getName. You can find that the return value of the method is String public String getName(String name) { return name; } }
/** * Create a test class to test the generic interface */ public class Test22 { public static void main(String[] args) { IgenericImpl t1 = new IgenericImpl(); System.out.println(t1.getName("wonendie")); Igeneric igeneric1 = new Igeneric() { @Override //The interface is referenced directly. There is no generic type given. Object is returned by default public Object getName(Object name) { return null; } }; Igeneric<String> igeneric2 = new Igeneric<String>() { @Override //When referencing an interface, the generic type is defined as String. When overriding a method, String is returned directly public String getName(String name) { return null; } }; } }
9.2.3 generic methods
It can also be used in the defined generics. However, we often need to use generics on only one method. At this time, we can use generic methods.
Generic method refers to defining the parameter type of a method as generic, so as to accept different types of parameters when calling. There can be multiple type parameters separated by commas, such as < K, V >. When defining, type parameters are usually placed in front of the return value.
When calling a generic method, you don't need to tell the compiler what type it is like a generic class. The compiler can automatically infer the type.
9.2.3.4 non static method
Grammatical structure
Public < generic notation > void getname {}
Public < generic notation > generic notation getname (generic notation name){
}
Examples
/** * Define a generic method */ public class MethodGeneric { /** * Defines a generic method with no return value * @param name * @param <T> */ public <T> void setName(T name){ System.out.println(name); } /** * Defines a generic method with a return value * @param name * @param <T> * @return */ public <T> T getName(T name){ return name; } }
/** *Call generic method */ public class Test33 { public static void main(String[] args) { MethodGeneric methodGeneric = new MethodGeneric(); /** * You can see that you can pass any type */ methodGeneric.setName("oldru"); methodGeneric.setName(1233333); MethodGeneric methodGeneric11 = new MethodGeneric(); System.out.println(methodGeneric11.getName(12333)); System.out.println(methodGeneric11.getName("dsfdfd")); } }
9.2.3.5 static method
When using generics in static methods, you should pay attention to one situation, that is, static methods cannot access the generics defined on the class; If the reference data type of static method operation is uncertain, the generic type must be defined on the method
public class Generic <T>{ private T flag; public void setFlag(T flag){ this.flag = flag; } /** * Define the error reason of static method: generics defined in the class are not allowed in static methods * This is an important difference between generic non static methods and generic static methods * @param name * @return */ public static T demo(T name){ return null; //Error: in static methods, generics defined in a class are not allowed } public T getFlag(){ return this.flag; } }
Grammatical structure
public static <Generic representation symbol> void getName(Generic representation symbol name){ } public statci <Generic representation symbol> Generic representation symbol getName(Generic representation symbol name){ }
Examples
/** * Define a static generic method */ public class MethodGeneric { public static <T> void setFlag(T flag){ System.out.println(flag); } public static <T> T getFlag(T flag){ return flag; } }
Call static methods. Static method calls do not need to be instantiated. They can be called directly through the class name
public class Test44 { public static void main(String[] args) { //Static method calls do not need to be instantiated, but can be called directly through the class name MethodGeneric.setFlag("oldlu"); int a = MethodGeneric.getFlag(123); System.out.println(a); } }
9.2.4 generic methods and variable parameters
In generic methods, generics can also define variable parameter types
Grammatical structure
public <Generic representation symbol> void showMsg(Generic representation symbol...agrs){ }
Examples
/** * Define a generic method with variable parameters */ public class MethodGeneric { public <T> void method(T...args){ //Variable parameter is an array, which can be traversed directly //Enhanced for loop traversal array for(T t:args){ System.out.println(t); } } }
Call generic method
public class Test5 { public static void main(String[] args) { MethodGeneric methodGeneric = new MethodGeneric(); String[] arr = new String[]{"a","b","c"}; methodGeneric.method(arr); Integer[] arr2 = new Integer[]{1,2,3}; methodGeneric.method(arr2); } }
9.2.5 wildcards and upper and lower limits
9.2.5.1 unbounded wildcards (171 sets 6:10) don't know much. Look back
“?” Represents a type wildcard, which is used in place of a specific type. It can only be used in "< >". It can solve the problem when the specific type is uncertain
Grammatical structure
public void showFlag(Generic<?> generic){ }
Examples
/* *Creating methods with wildcards */ public class ShowMsg { public void showFlag(Generic<?> generic){ System.out.println(generic.getFlag()); } }
call
/** * Call method */ public class Test6 { public static void main(String[] args) { ShowMsg showMsg = new ShowMsg(); Generic<Integer> generic = new Generic<>(); generic.setFlag1(20); showMsg.showFlag(generic); Generic<Number> generic1 = new Generic<Number>(); showMsg.showFlag(generic1); Generic<Integer> generic2 = new Generic<Integer>(); showMsg.showFlag(generic2); } }
9.2.5.2 upper limit of wildcard
The upper limit limit indicates that the type of wildcard is t class and subclass of t class or T interface and sub interface of T interface.
This method is also applicable to the upper limit of generics
Grammatical structure
What is this Generic?
public void showFlag(Generic<? extends Number generic){ } /** *there?Inherit from Number therefore?Only Number perhaps Number Subclass of
Example:
1. The wildcard has an upper limit. When calling this method, the parameters passed in can only be its subclasses