Object oriented concept
Process oriented & object oriented
-
Process oriented thought
- The steps are clear and simple. What to do in the first step and what to do in the second step
- Facing the process, it is suitable to deal with some relatively simple problems
-
Object oriented thought
- Birds of a feather flock together in a classified thinking mode. When thinking about problems, we will first solve what classifications are needed, and then think about these classifications separately. Finally, process oriented thinking is carried out on the details under a certain classification.
- Object oriented is suitable for dealing with complex problems and problems requiring 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.
What is object oriented
- Object oriented programming (OOP)
- The essence of object-oriented programming is to organize code in the way of class and data in the way of object.
- Core idea: abstraction
- Three characteristics:
- encapsulation
- inherit
- polymorphic
- From the perspective of epistemology, there are objects before classes. Objects are concrete things. Class is abstract, which is the abstraction of objects
- From the perspective of code operation, there are classes before objects. A class is a template for an object.
method
-
Method of definition
- Modifier
- Return type
- The difference between break and return
- Method name: pay attention to the specification, see the meaning of the name
- Parameter list: (parameter type, parameter name) indefinite item parameter (...)
- Exception throw
-
Method call
- Static method
- Non static method
- Formal and argument
- Value passing and reference passing
- this keyword
Method definition code example
//Demo01_methodDef class public class Demo01_methodDef { //main method public static void main(String[] args) { } /* Modifier return value type method name (parameter type parameter name){ ... //Method body; ... return Return value; } */ public String sayHello(){ return "hello,world"; } //Method with null return value public void print(){ return; } //Method with exception throw public void readFile(String file) throws IOException{ } }
Static and non static method code examples
public class Demo02_methodCall { //static method //Non static method public static void main(String[] args) { //Call static method Student.staticPrint(); //Call non static method Student student = new Student(); student.print(); //The types of formal parameters and arguments should correspond to each other one by one int add = Demo02_methodCall.add(1,2); } public static int add(int a, int b){ return a + b; } } //Student class class Student { //Static method: it is loaded with the class, so non static method cannot be called public static void staticPrint() { System.out.println("hello,world"); //print();// Non static methods cannot be called } //Class does not exist until it is instantiated public void print(){ System.out.println("hello,world"); } }
Value passing code example
//pass by value public class Demo03_passByValue { public static void main(String[] args) { int a = 1; System.out.println(a);//Output 1 Demo03_passByValue.change(a); System.out.println(a);//Output 1 } //The return value is null public static void change(int a){ a = 10; } }
Reference passing code example
//Reference passing: object, essence or value passing public class Demo04_passByReference { public static void main(String[] args) { Person person = new Person(); System.out.println(person.name);//Output null Demo04_passByReference.change(person); System.out.println(person.name);//Output handsome man } public static void change(Person person){ person.name = "handsome guy"; } } //Define a Person class with an attribute: name class Person{ String name;//The default value is null }
Classes and objects
-
Class is an abstract data type. It is the overall description / definition of a certain kind of things, but it can not represent a specific thing.
- Animals, plants, mobile phones, computers
- Person class, Pet class, Car class, etc. these classes are used to describe / define the characteristics and behavior of a specific thing
-
Objects are concrete instances of abstract concepts
- Zhang San is a concrete example of man, and Wang CAI in Zhang San's family is a concrete example of dog.
- It is a concrete instance rather than an abstract concept that can reflect the characteristics and functions.
Create and initialize objects
- Create an object using the new keyword
- When using the new keyword, in addition to allocating memory space, the created object will be initialized by default and the constructor in the class will be called.
- Constructors in classes, also known as construction methods, must be called when creating objects. And the constructor has the following two characteristics:
- Must be the same as the name of the class
- There must be no return type and void cannot be written
- Constructors must master
Code example
Class definition code:
//Person class public class Person { //Properties: Fields String name;//Default null int age;//Default 0 //constructor Person(){ } Person(String name,int age){ this.name = name; this.age = age; } //method public void study(){ System.out.println(this.name + "I'm learning"); } }
Test class:
//There should be only one main method in a project public class Application { public static void main(String[] args) { //Class: abstract, instantiated //Class instantiation will return an object of its own! //xiaohong object is a concrete instance of Student class! Person xiaohong = new Person(); Person xiaoming = new Person("xiaoming",3); System.out.println(xiaohong.name);//null System.out.println(xiaohong.age);//null xiaohong.name = "xiaohong"; xiaohong.age = 18; System.out.println(xiaohong.name);//xiaohong System.out.println(xiaohong.age);//18 xiaoming.study();//Call method } }
Operation results
😄 Check the class file. There are five java methods. Add the corresponding out folder to complete the compiled class file
Class constructor
-
characteristic:
- The method name is the same as the class name
- no return value
-
effect:
- new essentially calls constructor methods
- Initializes the value of the object
-
idea shortcut: Alt+insert
-
⭐ * * Note: * * if you want to use a parameterless construct after defining a parameterless construct, you must explicitly define a parameterless construct.
Code example
//Person class public class Person { //Properties: Fields String name;//Default null int age; //constructor //Even if a class doesn't write anything, it will have an implicit constructor method (no parameters, default value) //Add constructor shortcut Alt+insert //No parameter constructor. If there is no constructor, this is the implicit constructor method Person(){ } //Parameterized constructor: once a parameterized construct is defined, it must be explicitly defined to use a nonparametric construct Person(String name, int age){ this.name = name; this.age = age; } }
//There should be only one main method in a project public class Application { public static void main(String[] args) { //Class: abstract, instantiated //Class instantiation will return an object of its own! //xiaohong object is a concrete instance of Student class! Person xiaohong = new Person(); Person xiaoming = new Person("xiaoming",3); System.out.println(xiaoming.name);//xiaoming System.out.println(xiaoming.age);//3 } }
Create object memory analysis
Code example
public class Pet { public String name; public int age; public void shout(){ System.out.println("Let out a cry"); } }
public class Application { public static void main(String[] args) { Pet dog = new Pet(); dog.name = "Wangcai"; dog.age = 3; dog.shout(); Pet cat = new Pet(); } }
Sample diagram of memory analysis
Three characteristics
encapsulation
- The dew that should be exposed, the hide that should be hidden
- Our programming should pursue * * "high cohesion, low coupling" * *.
- High cohesion means that the internal data operation details of the class are completed by themselves, and external interference is not allowed;
- Low coupling: only a small amount of methods are exposed for external use.
- Encapsulation (data hiding)
- Generally, direct access to the actual representation of data in an object should be prohibited, but should be accessed through the operation interface, which is called information hiding.
- It's enough to remember this sentence: property private, get/set
advantage:
- Improve program security and protect data
- Implementation details of hidden code
- Unified interface
- The maintainability of the system has increased
Code example
//Class private: private public class Student { //Property private private String name;//name private int id;//Student number private char sex;//Gender private int age;//Age //Provide some methods that can manipulate this property //Provide some public get and set methods //get this data public String getName() { return name; } //set sets 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; } public int getAge() { return age; } public void setAge(int age) { if(age<0||age>120){//Illegal input this.age = 3; }else{ this.age = age; } } }
inherit
- The essence of inheritance is to abstract a group of classes, 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! A son has only one father, and a father can have multiple sons.
- Inheritance is a relationship between classes. In addition, the relationships between classes include dependency, composition, aggregation and so on.
- Two classes of inheritance relationship, one is a child class (derived class) and the other is a parent class (base class). The subclass inherits from the parent class and is represented by the keyword extends.
- In Java, all classes inherit the Object class directly or indirectly by default
- In a sense, there should be an "is a" relationship between subclasses and superclasses
- object class
- super
- Method rewrite
- A class modified by final cannot be inherited
Code example
//Parent class public class Person { public String name; private int money = 1_0000_0000;//10 thousand public void say(){ System.out.println("Said a word"); } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getMoney() { return money; } public void setMoney(int money) { this.money = money; } }
// Student is person // Student: derived class, subclass // If a subclass inherits the parent class, it will have all the methods of the parent class public class Student extends Person{ //Ctrl + H view inheritance relationship }
//Run class public class Application { public static void main(String[] args) { Student student = new Student(); //System.out.println(student.money);// Private member, subclass inaccessible System.out.println(student.getMoney());//The public methods of the parent class can access the private members of the parent class student.say();//The subclass inherits the method of the parent class } }
super
super note:
- super calls the constructor of the parent class, which must be in the first place of the constructor
- super must only appear in subclass methods or constructor methods!
- Super and this cannot call construction methods at the same time! (because super(); And this(); Must be on the first line)
Different from this:
-
The objects represented are different:
- this: the caller itself is the object
- super: represents the name of the parent object
-
Application premise
- this: it can be used without inheritance
- super: can only be used in inheritance conditions
-
Construction method
- this(); Construction of this class
- super(): Construction of parent class!
Code example
//Parent class public class Person { protected String name = "father"; Person(){ System.out.println("Person The parameterless construct is executed"); } public void print(){ System.out.println("Person"); } private void printPrivate(){ System.out.println("PersonPrivate"); } }
// Student: derived class, subclass public class Student extends Person { private String name = "son"; Student(){ //Hidden code. If the parent constructor is not explicitly called, the parent parameterless constructor is called by default super();//Calling a parent constructor or another constructor of a subclass must be on the first line of the constructor System.out.println("Student The parameterless construct is executed"); } Student(String name){ this(); this.name = name; } public void print(){ System.out.println("Student"); } public void testPrint(){ print(); this.print(); super.print(); //super.printPrivate();// The private method of the parent class cannot be accessed } public void testName(String name){ System.out.println(name); System.out.println(this.name); System.out.println(super.name); } }
//Execution class public class Application { public static void main(String[] args) { Student student = new Student(); student.testName("name"); student.testPrint(); } }
Operation results
rewrite
Override: inheritance relationship is required. Subclass overrides the method of parent class!
- characteristic:
-
Method names must be the same
-
The parameter list must be the same
-
Modifier: the scope can be expanded but not reduced. Public > protected > Default > private
-
Exception thrown: the scope can be reduced, but not expanded;
Exception (large) - > classnotfoundexception
When overridden, the method of the subclass must be consistent with that of the parent class; Different methods!
- Why rewrite?
- The function of the parent class and the subclass are not necessarily required or satisfied!
- Shortcut key
- Alt + Insert ; ( override;)
Code example
//Parent class public class B { public static void test(){ System.out.println("B->test()"); } public void test1(){ System.out.println("B->test1()"); } }
//Subclass //Rewriting is the rewriting of methods, which has nothing to do with properties public class A extends B{ public static void test(){ System.out.println("A->test()"); } //Override: override @Override //Annotation: functional annotation public void test1() { System.out.println("A->test1()"); } }
//Execution class public class Application { //Static methods are very different from non static methods public static void main(String[] args) { //Static method: the method call is only related to the left, that is, the defined data type A a = new A(); a.test();//A //The reference of the parent class points to A B b = new A(); b.test();//B //Non static method: the subclass overrides the method of the parent class a.test1();//A b.test1();//A } }
Operation results
The override is for non static methods.
java access rights
- public: visible to all classes. Objects used: classes, interfaces, variables, methods
- protected: visible to classes and all subclasses in the same package. Use object: variable, method. Note: cannot decorate class (external class)
- default: visible in the same package without any modifiers. Use objects: classes, interfaces, variables, methods.
- private: visible in the same category. Use object: variable, method. Note: cannot decorate class (external class)
polymorphic
- That is, the same method can adopt 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 the object
- Conditions for the existence of 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.
- Type conversion of instanceof reference type
Polymorphic considerations
-
Polymorphism is the polymorphism of methods, and there is no polymorphism of attributes
-
There is a connection between the parent class and the child class, otherwise an error will be reported and the type conversion exception will be reported! CLassCastException !
-
Existence conditions: inheritance relationship, method needs to be rewritten, and parent class reference points to child class object!
Father f1 = new Son( );
Methods that cannot be overridden
- static method belongs to class, not instance.
- final constant
- private method
Code example
//Parent class public class Person { public void run() { System.out.println("Person run"); } public void play(){ System.out.println("Person play"); } }
//Subclass public class Student extends Person{ @Override public void run() { System.out.println("Student run"); } public void eat(){ System.out.println("Student eat"); } }
//Execution class public class Application { public static void main(String[] args) { //The actual type of an object is determined new Person(); new Student(); //The type of reference that can be pointed to is uncertain: the reference of the parent class points to the child class //Student s can call their own or parent class methods Student student = new Student(); //Person parent type, which can point to subclasses, but cannot call methods unique to subclasses Person person = new Student(); Object object = new Student(); //The methods that can be executed by an object mainly depend on the type on the left of the object, which has little to do with the right //Methods unique to the parent class student.play();//A subclass can call the methods of its parent class person.play(); //Subclass overrides the method of the parent class student.run(); person.run();//The subclass overrides the method of the parent class, and the type reference still executes the method of the subclass //Methods unique to subclasses student.eat(); //person.eat();// Parent class cannot call ((Student) person).eat();//Methods that can execute subclasses after cast } }
Operation results
instanceof
boolean result = obj instanceof Class;
Where obj is an object and Class represents a Class or an interface. When obj is an object of Class, or its direct or indirect subclass, or the implementation Class of its interface, the result returns true, otherwise false.
Note: the compiler will check whether obj can be converted to the class type on the right. If it cannot be converted, an error will be reported directly (compilation fails). If the type cannot be determined, it will be compiled. See the runtime for details.
Code example
public class Application { public static void main(String[] args) { //Object > String //Object > Person > Student //Object > Person > Teacher Object object = new Student(); System.out.println(object instanceof Student);//true System.out.println(object instanceof Person);//true System.out.println(object instanceof Object);//true System.out.println(object instanceof Teacher);//true System.out.println(object instanceof String);//false System.out.println("======================"); Person person = new Student(); System.out.println(person instanceof Student);//true System.out.println(person instanceof Person);//true System.out.println(person instanceof Object);//true System.out.println(person instanceof Teacher);//false //System.out.println(person instanceof String);// Compilation error System.out.println("======================"); Student student = new Student(); System.out.println(student instanceof Student);//true System.out.println(student instanceof Person);//true System.out.println(student instanceof Object);//true //System.out.println(student instanceof Teacher);// Compilation error //System.out.println(person instanceof String);// Compilation error System.out.println("======================"); /* Whether the compilation can pass, look at the left. The operation results are shown on the right */ } }
Operation results
The compiler check is based on the reference type, and the running result is based on the actual type of the reference object. That is, whether the compilation can be done by looking at the reference type description on the left and the actual object structure on the right.
Type conversion
Summary of polymorphism:
- The parent class refers to an object that points to a child class
- If you convert a subclass to a parent class and type up, you may lose the subclass's own methods.
- Convert the parent class to a child class, type down and cast. The child class can call the methods of the parent class.
- Convenient method call, reduce repeated code, concise.
Code example
//Parent class public class Person { public void run(){ System.out.println("Person run "); } }
//Subclass public class Student extends Person{ public void say(){ System.out.println("Student say"); } }
public class Application { public static void main(String[] args) { //Type conversion //High ----------- > low Person obj = new Student(); //Automatic up type conversion obj.run();//Call parent method //obj.say();// Method of missing subclass in up type conversion ((Student)obj).say();//Convert parent class to child class and force type conversion ((Student)obj).run();//A subclass can call the methods of its parent class } }
Operation results
Supplementary static
- Static code block
- Static import
- final modifier class cannot be inherited
Code example
public class Person { //2: Assign initial value~ { //Code block (anonymous code block) System.out.println("Anonymous code block"); } //1 static{ //Static code block, executed only once System.out.println("Static code block"); } //3 public Person() { System.out.println("Construction method"); } public static void main(String[] args) { Person person = new Person(); System.out.println(); } }
results of enforcement
abstract class
- The abstract modifier can be used to modify a method or a class. If you modify a method, the method is an abstract method; If you modify a class, it is an abstract class.
- Abstract classes can have no abstract methods, but classes with abstract methods must be declared as abstract classes.
- An abstract class cannot create an object by using the new keyword. It is used to let subclasses inherit.
- Abstract methods have only method declarations and no method implementations. They are used to implement subclasses.
- If a subclass inherits an abstract class, it must implement the abstract method that the abstract class does not implement, otherwise the subclass must also be declared as an abstract class.
Code example
//Abstract abstract class //Classes can only inherit single, but interfaces can inherit multiple public abstract class Action { //Constraint ~ someone helped us achieve it~ //Abstract, abstract method, only method name, no method implementation public abstract void doSomething(); public void hello(){ } public Action() { System.out.println("Abstract class constructor"); } /* characteristic: 1. You can't use the abstract class new, you can only rely on subclasses to implement it; constraint 2. Ordinary methods can be written in abstract classes 3. Abstract methods must be in abstract classes Abstract abstract Thinking questions: 1. Can't new? Is there a constructor 2. The significance of abstract classes to improve development efficiency */ }
//All methods of an abstract class that inherit its subclasses must implement its methods. Unless the subclass is also an abstract class public class A extends Action{ public A() { System.out.println("Subclass constructor"); } @Override public void doSomething() { } }
public class Application { public static void main(String[] args) { A a = new A(); } }
Operation results
Interface
Three differences
- Common 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
understand
- An interface is a specification. It defines a set of rules, which embodies the idea of "if you are..., you must be able to..." in the real world. If you are an angel, you must be able to fly. If you are a car, you must be able to run. If you are a good man, you must kill the bad man; If you are a bad person, you must bully the good person.
- The essence of interface is contract, just like the law between us. After making it, everyone will abide by it.
- The essence of object-oriented is the abstraction of objects. The interface can best reflect this. Why we discuss design patterns only for languages with abstract ability (such as c + +, java, c, etc.) is because what design patterns study is actually how to abstract reasonably.
- The keyword for declaring a class is class, and the keyword for declaring an interface is interface
characteristic
- constraint
- Define some methods to let different people realize their hearts
- public abstract method
- public static final constant
- The interface cannot be instantiated. There is no constructor in the interface
- implements can implement multiple interfaces
- You must override the methods in the interface
Code example
//Interface 1 public interface UserService { //All members in the interface are constants public static final public static final int age = 99; String name = "name"; //All definitions in the interface are actually Abstract public abstract void add(String name); void delete(String name); void update(String name); void query(String name); void timer(); }
//Interface 2 public interface TimeService { int age = 2; void timer(); }
//Abstract class: Extensions single inheritance //Class can implement the implements interface //To implement the class of the interface, you need to rewrite the methods in the interface //Using interface to realize pseudo multi inheritance //Implementation class public class UserServiceImpl implements UserService,TimeService{ @Override public void add(String name) { } @Override public void delete(String name) { } @Override public void update(String name) { } @Override public void query(String name) { } @Override public void timer() { System.out.println("timer"); System.out.println(TimeService.age); System.out.println(UserService.age); //System.out.println(age);// Compilation error System.out.println(name); } }
//Test class public class App{ public static void main(String[] args) { TimeService time = new UserServiceImpl(); time.timer(); UserService user = new UserServiceImpl(); user.timer(); } }
Operation results
Inner class
Internal class is to define a class inside a class. For example, if a class B is defined in class A, class B is called internal class relative to class A, and class A is external class relative to class B.
Internal class classification
- Member inner class
- Static inner class
- Local inner class
- Anonymous Inner Class
Code example
//There can be multiple classes in a java class, but there can only be one public class public class Outer { private int id = 10; public void out(){ System.out.println("This is the method of an external class"); } public void metho(){ //Local inner class class Inner{ public void in(){ } } } //Member inner 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); } } //Static inner class public static class StaticInner{ public void in(){ System.out.println("This is the method of the inner class"); } } }
//Test class public class Application { public static void main(String[] args) { Outer outer = new Outer(); //Instantiate the inner class through the outer class Outer.Inner inner = outer.new Inner(); inner.in();//This is the method of the inner class inner.getId();//10 //There is no name to initialize the class, so there is no need to save the instance to the variable new Outer().out();//This is the method of an external class //Anonymous Inner Class UserService userService = new UserService() { @Override public void add(String name) { } @Override public void delete(String name) { } @Override public void update(String name) { } @Override public void query(String name) { } @Override public void timer() { } }; } } Class method"); } //Get the private properties of the external class public void getId(){ System.out.println(id); } } //Static inner class public static class StaticInner{ public void in(){ System.out.println("This is the method of the inner class"); } } }
//Test class public class Application { public static void main(String[] args) { Outer outer = new Outer(); //Instantiate the inner class through the outer class Outer.Inner inner = outer.new Inner(); inner.in();//This is the method of the inner class inner.getId();//10 //There is no name to initialize the class, so there is no need to save the instance to the variable new Outer().out();//This is the method of an external class //Anonymous Inner Class UserService userService = new UserService() { @Override public void add(String name) { } @Override public void delete(String name) { } @Override public void update(String name) { } @Override public void query(String name) { } @Override public void timer() { } }; } }