object-oriented programming
catalog:
1, First knowledge of object-oriented
2, Methods review and deepen
3, Object creation analysis
4, Three characteristics of object oriented
5, Abstract classes and interfaces
6, Internal classes and
1, First knowledge of object-oriented
Process oriented & object oriented
*Process oriented thought
- The steps are clear and simple. What do you do in the first step and the second part
- Process oriented is suitable for dealing with some relatively simple problems
*Object oriented thought
-
Birds of a feather flock together, the thinking mode of classification. When thinking about problems, we should first think about what classifications are needed to solve problems, and then think about these classifications separately. It is best to think process oriented about the details under a certain classification.
-
When object-oriented, it is suitable for dealing with complex problems that require multi person cooperation!
*For describing complex things, in order to grasp them macroscopically and analyze them reasonably as a whole, we need to use object-oriented thinking to analyze the whole system. However, specific to micro operation, it still needs process oriented thinking to deal with it.
2, Methods review and deepen
package OOP.demo01; //Demo01 class public class Demo01 { //main method public static void main(String[] args) { } /*Statement format of write method: Modifier return value type method name (parameter){ //Method body return Return value; } */ public String sayHello(){ return "hello,world"; } //Method for comparing the size of two numbers //return ends the method and returns a result! public int max(int a,int b){ return a>b ? a :b;//The ternary operator outputs a if a > b, otherwise B } }
Non static method call
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-oke2krkg-1634893705484) (C: \ users \ 86150 \ appdata \ roaming \ typora user images \ image-20211021162216940. PNG)]
Static method call
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-kxhm35hm-1634893705486) (C: \ users \ 86150 \ appdata \ roaming \ typora \ user images \ image-2021102116303328. PNG)]
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-xkgod7iz-1634893705487) (C: \ users \ 86150 \ appdata \ roaming \ typora user images \ image-20211021163449153. PNG)]
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-iwtl3fvp-1634893705488) (C: \ users \ 86150 \ appdata \ roaming \ typora user images \ image-20211021164312773. PNG)]
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-ly61dzzm-1634893705488) (C: \ users \ 86150 \ appdata \ roaming \ typora \ user images \ image-20211021165220770. PNG)]
3, Object creation analysis
package OOP.demo01; //Reference passing: object, essentially passing value public class Demo05 { public static void main(String[] args) { Perosn person = new Perosn(); System.out.println(person.name);//null Demo05.change(person); System.out.println(person.name); } public static void change(Perosn perosn){ //Perosn is an object that points to = = = Perosn person = new Perosn(); perosn.name = "Long huawang";} } //Defines a Perosn class with an attribute: name class Perosn{ String name = "Long huawang"; }
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-gea1je31-1634893705489) (C: \ users \ 86150 \ appdata \ roaming \ typora \ typora user images \ image-20211021191223658. PNG)]
*Alt + insert new key a constructor
package OOP.demo03; //java--->clss public class Person { //Even if a class writes nothing, it will have a method //Display definition constructor String name; int age; //Alt + insert //1. Using the new keyword is essentially calling the constructor //2. Used to initialize values public Person(){ } //Parametric Construction: once a parametric construction is defined, a nonparametric construction must display the definition public Person(String name){ this.name = name; } public Person(String name,int age){ this.name = name; this.age = age; } }
package OOP.demo03; public class Application { public static void main(String[] args) { //new materializes an object Person person = new Person("Long huawang",23); System.out.println(person.name); } }
encapsulation
-
What should be leaked, what should be hidden
-
Our program design requires "cohesion and low coupling". High cohesion: the internal structure of the class, the details of data operation are completed by ourselves, and external dryness is not allowed. Low coupling: only a small number of methods are exposed for external use.
-
Encapsulation (hidden data)
-
Generally, access to the actual representation in an object should be prohibited, but should be accessed through the operation interface, which is called hidden information.
-
It's enough to remember this sentence: property private, get/set
package OOP; import OOP.demo04.Student; /* get set Benefits of encapsulation 1.Improve program security and protect data 2.Hidden code implementation details 3.Unified interface 4.System maintainability increased */ public class Application { public static void main(String[] args) { Student s1 = new Student(); s1.setName("Long huawang"); System.out.println(s1.getName()); } }
package OOP.demo04; //Class private: private public class Student { //Property private private String name; //full name private int id;//Student number private char sex; //Gender //Because properties are private //We want to provide some methods that can operate these properties! //That is, the get and set methods of public //get gets this data public String getName(){ return this.name; } //The set method sets a value for this data public void setName(String name){ this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public char getSex() { return sex; } public void setSex(char sex) { this.sex = sex; } }
-
inherit
-
The essence of inheritance is the abstraction of a certain group, so as to realize better modeling of the real world.
-
Extensions means "extension". A subclass is an extension of a parent class.
-
java classes only have single inheritance, not multiple inheritance!
-
Inheritance is a kind of relationship between classes. In addition, the relationship between classes includes dependency, composition, aggregation and so on.
-
Two classes of inheritance relationship, one is the subclass (derived class) and the other is the parent class (base class). The subclass inherits the parent class and is represented by the keyword extends.
-
In a sense, there should be a "is a" relationship between a child class and a parent class.
super (method of calling parent class)
- super calls the constructor of the parent class, which must be in the first instance of the constructor
- super must only appear in subclass methods or constructor methods!
- super and thi cannot call constructor at the same time!
vs this:
The objects represented are different:
this: the object itself is the caller
super: represents the application of the parent object
premise
this: can be used without inheritance
super: can only be used under inheritance conditions
Construction method
This (): the construction of this class
super(): Construction of parent class
rewrite
- Inheritance relationship is required. The subclass overrides the method of the parent class!
- Method names must be the same
- The parameter list must be the same
- Modifier: the scope can be expanded: public > protected > Default > private
- Exceptions thrown: the scope can be narrowed, but not expanded; classnotfoundexception -- > exception... Exceptions not found by the class
- When overridden, the methods of the child class and the parent class must be consistent, and the method bodies are different!
Why rewrite:
- 1. The function of the parent class and the subclass do not necessarily need or meet! Alt + Insert;override
polymorphic
- That is, the same method adopts many different behavior modes according to different sending objects.
- The actual type of an object is determined, but there are many types of references that can point to an object
- Conditions for polymorphism:
- There is an inheritance relationship
- Subclass overrides parent method
- A parent class reference points to a child class object
-
Note: polymorphism is the polymorphism of methods, and there is no polymorphism of attributes.
-
instanceof type conversion ···· reference type
-
package OOP; import OOP.demo06.Person; import OOP.demo06.Student; public class Application { public static void main(String[] args) { //The actual type of an object is determined // new Student(); // new Person(); //The type of reference that can be pointed to is uncertain: the reference of the parent class points to the child class //The methods that can be called by the subclass Student are their own or inherit the parent class! Student s1 = new Student(); //The parent class Person can point to subclasses, but cannot call methods unique to subclasses Person s2 = new Student(); Object s3 = new Student(); //Object can execute those methods, mainly depending on the type on the left of the object, which has little to do with the right s2.eat();//The subclass overrides the method of the parent class and executes the method of the subclass s1.sun(); } }
- Precautions:
-
Polymorphism is the polymorphism of methods, and there is no polymorphism of attributes
-
The parent and child classes can only be cast if they are related, otherwise there will be an exception: ClassCastException!
-
Polymorphic existence conditions: inheritance relationship, method needs to be rewritten, parent class reference points to child class object! father f1 = new Son();
What cannot be overridden:
- static method belongs to class, which does not belong to real column
- final constants cannot be changed
- private method
package OOP; import OOP.demo06.Person; import OOP.demo06.Student; public class Application { public static void main(String[] args) { //The actual type of an object is determined // new Student(); // new Person(); //The type of reference that can be pointed to is uncertain: the reference of the parent class points to the child class //The methods that can be called by the subclass Student are their own or inherit the parent class! Student s1 = new Student(); //The parent class Person can point to subclasses, but cannot call methods unique to subclasses Person s2 = new Student(); Object s3 = new Student(); //Object can execute those methods, mainly depending on the type on the left of the object, which has little to do with the right s2.eat();//The subclass overrides the method of the parent class and executes the method of the subclass s1.sun(); } }
5, Abstract classes and interfaces
abstract class
//Abstract abstract abstract class: Extensions: single inheritance (interfaces can inherit more) for example: socket public abstract class Action{ //Constraints... Someone can help us achieve them //Abstract, abstract method, only method name, no method implementation public void doSomething(){ //1. This abstract class cannot be new. It can only be implemented by subclasses: constraint function //2. Ordinary methods can be written in abstract classes~ //3. Abstract methods must be in abstract classes //Abstract: Constraints //Significance of abstract class: it is equivalent to defining a template in the abstract to ~ improve the development efficiency } }
Interface
Keyword of interface: Interface
Ordinary class: only concrete implementation
Abstract classes: concrete implementations and specifications (abstract methods) are available
Interface: only specification! I can't write methods ~ professional constraints! Separation of constraints and Implementation: interface oriented programming~
- An interface is a specification, a set of rules defined, which embodies the idea of "if you are... You must be able to..." in the implementation world. If you are an angel, you must be able to fly. If you are a boat, you must be able to get into the water. If you are a car, you must be able to run and so on
- The essence of an interface is a contract, just like the laws among us. After it is formulated, everyone will abide by it.
- The essence of OOP is the abstraction of objects, which is best reflected in the interface. Why we discuss design patterns only for languages with abstract ability (such as C,C++,java,C# etc.) is because what design patterns study is actually how to abstract reasonably.
//Class can implement multiple interfaces and connect using implements //If you implement the class of the interface, you need to rewrite the methods in the interface~ public class UserServiceImpl implements UserService{ }
package OOP.demo07; //Abstract thinking needs exercise, //The keyword defining the interface: interface. All interfaces need to have implementation classes public interface UserService { //The attributes defined in the interface are constants ~ public static final int AGE = 99; //All definitions in the interface are actually Abstract public abstract s void add(String name); void delete(String name); void update(String name); void query(String name); }
- Function of interface:
- constraint
- Define some methods for different people to implement~
- The methods inside are all public abstract
- All constants are public static final static constants
- The interface cannot be materialized. There is no constructor in the interface
- Interface can implement multiple interfaces through implements
- Methods in interfaces must be overridden
6, Inner class
Inner class
- Internal class is to define a class within a class. For example, if a class B is defined in class A, then B is the internal class of class A, and the opposite class A is the external class of class B.
- Member inner class
package OOP.demo8; public class Outer { private int id = 10; public void out(){ System.out.println("This is the method of an external class"); } public class Inner{ public void in(){ System.out.println("This is the method of the inner class"); } //Get the private properties of the external class~ public void getID(){ System.out.println(id); } } }
package OOP; import OOP.demo8.Outer; import static java.lang.System.out; public class Application { public static void main(String[] args) { //Call external class new Outer outer = new Outer(); //Call the inner class and instantiate the inner class through the outer class Outer.Inner inner = outer.new Inner(); inner.getID(); } }
2. Static internal class
public class Inner{ public void in(){ System.out.println("This is the method of the inner class"); } //Get the private properties of the external class~ pricate void getID(){ //Change public to private System.out.println(id); } }
3. Local internal class
package OOP.demo8; public class Outer { //Local inner class public void method(){ class Inner{ } } }