Move towards the goal of Java programmers!
day16
Object oriented - continued 6
Interface - continued
Formal parameter problem
The formal parameter of the method passes the basic data type or reference data type. If the formal parameter is a basic data type, the actual parameter is the current corresponding data value, and the change of the formal parameter will not affect the actual parameter, which is relatively simple. If the formal parameter refers to the data type, the actual parameter is the current corresponding spatial address value.
The formal parameter of the method is the analysis when referencing a data type:
- (if the reference data type is) concrete class: the actual parameter should create the current concrete class object
- Abstract class: the actual parameters need to pass the subclass object that should create the current abstract class (abstract class polymorphism)
- Interface: first define the sub implementation class of the interface, and then pass the anonymous object of the sub implementation class in the actual parameters. (interface polymorphism)
- Array: the actual parameter needs to pass the array object
Now we can finally complete the data type diagram of week1
Exercise: cat and dog case with interface as formal parameter
/** * Design a Java program * (1)Define an interface CanCry and describe the roaring method public void cry() * (2)Define Dog and Cat respectively and implement CanCry interface. The functions of the implementation methods are: * Printout "I'm a dog, my bark is woof woof", "I'm a cat, my bark is meow meow" * (3)Define a main class G, * Define a void makecry (cancry C) method, which makes the roaring thing roar. * Create dog object (dog), cat object (CAT) and G object (g) in main method * g Call the makecry method to make dogs and cats roar. */ //Define an interface CanCry and describe the roaring method public void cry() interface CanCry { public void cry() ; } //Cats class Cat implements CanCry { @Override public void cry() { System.out.println("I'm a cat. My cry is meow meow"); } } //Dogs class Dog implements CanCry { @Override public void cry() { System.out.println("I'm a dog. My bark is barking"); } } //Test class class G { public static void main(String[] args) { //Create class G objects G g = new G() ; //Method 1: create a specific object name: interface polymorphism //Actual parameter: the interface subclass object needs to be passed CanCry canCry = new Dog() ; g.makeCry(canCry); canCry = new Cat() ; g.makeCry(canCry) ; System.out.println("------------------------") ; //Method 2: anonymous object g.makeCry(new Dog()) ; g.makeCry(new Cat()); } //Member method public void makeCry(CanCry c){ c.cry(); } }
Return value problem
The return value of a method is either a basic data type or a reference data type. If the return value of a method is a basic data type, the corresponding type is used to receive the type in the method declaration. This is introduced in the previous learning method. In the later stage, we learn all about reference data types.
The return value of the method is the analysis when referring to the data type:
- (if the return value of the method is) specific class: what needs to be returned is the specific object of the current class!
- Abstract class: what needs to be returned is the subclass object of the current abstract class (it can also be returned in the form of anonymous object - abstract class polymorphism)
- Interface: what needs to be returned is the sub implementation class object of the interface (interface polymorphism)
Comparison of implementation effects between interface mode and inheritance mode
We give examples of these two methods, and finally summarize.
If we write a concrete class, it implements many functions (Methods). Then we define another class. When we want to override some of the above methods, we need to use inheritance. Then the use of inheritance produces method rewriting. Method rewriting will inherit all public access methods, which will lead to some methods being brought over even if we don't need them.
What will happen if you change to interface oriented programming? If we write an interface and define some abstract methods, then defining a new class to implement the interface requires the implementation of all the methods in the interface. If we need to rewrite the method, we will write another interface and put the method we want to rewrite into it. When we define a new class, we just need to rewrite the selected method.
We might as well describe it with examples in life. Class is equivalent to wholesale when buying vegetables, either all or none; The interface is equivalent to retail. You can have one or more or all of them.
To sum up, the implementation effect of interface is more flexible and advantageous than that of inheritance. Interface oriented programming is the main form of our future development.
Exercise: USB interface
/** * Requirements Description: * In real life, we often use some devices through the USB interface of the computer, * For example, mp3, mobile hard disk, USB flash drive, etc. Now it is required to use interface oriented programming to simulate and implement this example. * Implementation steps * (1)Create a USB interface in which only one work () method is defined. * (2)Create MP3 class and implement USB interface. * (3)Create a USB disk class (U_Disk) and implement the USB interface. * (4)Create a computer class and define a method using the interface useMobile(USB u). * (5)Create corresponding objects in the test class for testing (MP3 object, USB flash disk object and computer object) */ //Computer class Computer { //The computer itself uses mobile devices to check in different devices and realize different functions! //Privatize construction methods private Computer(){} //Provide static function public static void useMobile(USB u){ //When testing: the formal parameter of the method is an interface u.work() ; } } //MP3 class class MP3 implements USB { @Override public void work() { System.out.println("You can listen to music..."); } } //U SB flash disk class U_Disk implements USB { @Override public void work() { System.out.println("You can copy the file"); } } //USB interface interface USB { void work() ; } //Test class public class Test { public static void main(String[] args) { //Using the function of computer USB usb = new MP3() ; //Interface polymorphism Computer.useMobile(usb); usb = new U_Disk() ; //Interface polymorphism Computer.useMobile(usb) ; System.out.println("---------------------------------") ; Computer.useMobile(new MP3()); Computer.useMobile(new U_Disk()); } }
Inner class
If a class is defined inside other classes, this class is called an inner class. For example, if a class B is defined in a Class A, then class B is called the inner class of class A.
Location of inner class
According to the different positions of the internal class defined in the class, it can be divided into the following two formats:
- Member inner class: a class defined at the member position of an outer class
- Local inner class: a class defined in a member method of an outer class
Internal classes can be defined in classes, methods can be defined in classes, and internal classes can be defined in methods, but methods cannot be defined in methods.
Members in the inner class of members access the member variables of the outer class, including private variables
Use of member inner classes
Access methods of internal and external classes of members
Members in the inner class of a member can access the member variables of the outer class, including private properties
The member method of the external class accesses the method of the internal class of the member. You can create the internal class object and access the method. The format is as follows:
External class name.Internal class name object name = new External class object.Inner class object;
The external class accesses the member method of the internal class of the member. The internal class of the member of the external class should be regarded as the member of the external class, and the object should be created and accessed according to the format. There are static and non static formats for accessing member methods.
Access non static methods:
External class name.Internal class name object name = new External class name.Internal class name();
Access static method: it can be the access method of the object created above, or access as follows:
External class name.Internal class name object name = External class name.Internal class name.Method name();
Generally speaking, it will not be used in actual development. Because generally, internal classes are not directly accessed by the outside world.
Common modifiers for inner classes of members
- private: it can ensure the security of data
- static: make data access more convenient
matters needing attention:
-
If the inner classes of members are static, the methods of the inner classes of members have nothing to do with static, and the methods can only access the static outer class members.
-
Static methods cannot exist in non static member inner classes.
Interview question: there is no inheritance relationship between internal class and external class
/** * Look at the program and complete the code to make the program output 30, 20 and 10 on the console */ class Outer { public int num = 10; class Inner { public int num = 20; public void show() { int num = 30; //Complete these three codes System.out.println(); System.out.println(); System.out.println(); } } } class OuterDemo { public static void main(String[] args) { Outer.Inner oi = new Outer().new Inner(); oi.show(); } }
answer:
num this.num Outer.this.num perhaps new Outer().num
Use of local inner classes
Local inner classes can directly access members of external classes. You can create internal class objects and call internal class methods through objects to use the functions of local internal classes.
Features of local internal classes: local internal classes still access member variables of external classes, including private variables
Interview question: conditions for local internal classes to access local variables
Question: can local internal classes access local variables? What are the requirements for local variables?
answer:
Before jdk7 and jdk7, local variables must be displayed and modified with final, otherwise an error will be reported. jdk8 has optimized the jvm, and num2 is a constant at this time!
The life cycle of local variables exists with the call of methods and disappears with the end of the call of methods. After the current method is completed, the num2 local variable should no longer exist, but we are still using the internal class object to access its member methods. Objects are not immediately collected by the garbage collector, but objects without more references are collected when they are idle. Therefore, at this time, these variables are resident in memory and should be changed into constants using final.
Permission modifier
public | protected | default | private | |
---|---|---|---|---|
In the same category | √ | √ | √ | √ |
Subclasses of the same package, other classes | √ | √ | √ | |
Different steamed stuffed bun classes | √ | √ | ||
Other classes of different packages | √ |
Use of other modifiers
-
static: used in combination with custom constants and final
public static final Data type variable name = Initialization data;
Static can also be used in tool classes. The construction methods in tool classes are privatized, and the methods in them will be added to static and accessed using the class name.
-
Abstract: generally, it is a modified class, which is used as an abstract class. It can also be defined in member methods, such as in abstract classes:
public abstract Return value type method name(parameter list) ;
Abstract can be omitted from the abstract methods defined in the interface
Meaning of package and code layering
A package is a folder (directory). When we are developing a project, it is impossible to put all java files under one package. Therefore, in the real development environment, the package needs to be layered for the code.
Classification of packages in code
com.xxx.pojo/entity/domain: it stores entity classes that conform to the "JavaBean specification" and describe real-world things. Under this package, properties will be privatized and public access methods setter and getter will be provided. It can implement serializable interfaces (in distributed projects).
com.xxx.service: business interface layer, also known as service layer, is used to realize functions.
com.xxx.dao: database access layer, also known as persistence layer, is the interface layer of data access and connects to the database through JDBC.
com.xxx.controller: control layer. It is used to call the business layer data method and render the view of the data by using the front and rear end interaction technology!
Two common methods of Object class
Each class has Object as the superclass (parent class), and all classes inherit from Object by default
common method
public final Class getClass(): get the currently running Class object (bytecode file object)
In Class, public String getName() is used to obtain the name of the current Class or interface and return it in string form
public int hashCode(): understand that "an address value" is not an actual address value. It is calculated by the underlying hash algorithm (hash)
hashcode source code:
public native int hashCode();
The method of native modification is a local method, which is implemented by non Java language. The bottom layer is c-related language
public String toString(): returns the string representation of the object. The result should be concise and easy to read. It is recommended that all subclasses override this method.
toString source code:
public String toString() { //Package name Class name + @ + hexadecimal data return getClass().getName() + "@" + Integer.toHexString(hashCode()); }
When overriding the toString method, use the template provided by the development environment“
public boolean equals(Object obj): compare whether the objects are equal. The type is referenced to compare whether the address values are the same
==The difference between and equals
==: if the connection is of two basic data types: for example, the comparison in int is whether the data values are equal. If the connection is a reference type, the comparison is whether the address values are the same
equals() is a method of the Object class
Source code of equals:
public boolean equals(Object obj) { return (this == obj); }
If we do not override the equals method of Object, the default comparison is whether the address values of the two reference types are the same. If we override the equals method and override hashCode() at the same time, the comparison is whether the member information is the same!
Note: whenever you override the method equals(), you usually need to override the hashCode method
Blogs inevitably make some mistakes. If there is any problem with the writing, you are welcome to criticize and correct.