Java object oriented programming (OOP)
Process oriented and object oriented
- Process oriented
- The steps are clear and simple, what to do in the first step, what to do in the second part
- Process oriented is suitable for dealing with some simple problems
- object-oriented
- Birds of a feather flock together, the thinking mode of classification. 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.
Object oriented programming (OOP)
The essence of object-oriented: organize code in the way of class and organize (encapsulate) data in the way of object
Core knowledge points: abstraction and three characteristics (encapsulation, inheritance and polymorphism)
-
From the perspective of cognitive theory, 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.
Creation of classes and objects
Relationship between classes and objects
Class is an abstract data type. It is an overall description / definition of a class 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.
Creating and initializing 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.
//Student class public class Student { //Properties: Fields String name;//Default null int age;//Default 0 //method public void study(){ System.out.println(this.name+"Want to learn"); } }
public class Application { public static void main(String[] args) { //Class: abstract and needs to be instantiated //Class will return its own object after instantiation //A student object is a concrete instance of a student class Student stu1 = new Student(); Student stu2 = new Student(); stu1.name = "xiaoming"; stu1.age = 9; System.out.println(stu1.name);//xiaoming System.out.println(stu1.age);//9 System.out.println(stu2.name);//null System.out.println(stu2.age);//0 } }
Constructor details
- Constructors in classes, also known as constructor methods, must be called when creating objects. And the constructor has the following two characteristics:
- 1. Must be the same as the class name.
- 2. There must be no return type and void cannot be written.
public class Person { //Even if a class doesn't write anything, it will automatically generate a constructor //The definition constructor can also be displayed String name; int age; //Instantiation initial value //Using the new keyword is essentially calling the constructor //Used to initialize values public Person(){ //this.name = "longbao"; } //Parameterized Construction: once a parameterized construction is defined, the definition must be displayed for a nonparametric construction public Person(String name) { this.name = name; } //alt+insert shortcut public Person(String name, int age) { this.name = name; this.age = age; } /* Constructor: 1,Same as class name 2,no return value effect: 1,new The essence is to call the constructor 2,Initialize object value be careful: 1,After defining a parameterless construct, if you want to use a parameterless construct, you need to define a parameterless construct */ } //There should be only one main method in a project public class Application { public static void main(String[] args) { //new instantiation Person person = new Person("longshen"); System.out.println(person.name); } }
Create object memory analysis
https://www.bilibili.com/video/BV12J41137hu?p=65
Limited writing, it is recommended to watch the video
Encapsulation, inheritance, polymorphism
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.
Property private, get/set
//class public class Student { private String name; private int id; private char sex; private int age; //Provide some methods that can manipulate this property //public get/set //get this data public String getName(){ return this.name; } //set sets a value for this data public void setName(String name){ this.name = name; } //alt+insert 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>150||age<0){//wrongful this.age = 3; }else{ this.age = age; } } } ------------------------ public class Application { public static void main(String[] args) { Student s1 = new Student(); s1.setName("Liu Ao"); System.out.println(s1.getName()); s1.setAge(222);//wrongful System.out.println(s1.getAge()); } /* Meaning of encapsulation 1.Improve program security and protect data 2.Implementation details of hidden code 3.Unified interface 4.The maintainability of the system has increased ...... */ }
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!
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 a sense, there should be an "is a" relationship between a subclass and a parent class
//In java, all classes inherit Object directly or indirectly by default //Parent class public class Person { //public //protected //Default default //private private int money = 1000000; protected String name = "liuao"; public Person() { System.out.println("Person Nonparametric execution"); } public void say(){ System.out.println("shuohua"); } public int getMoney() { return money; } public void setMoney(int money) { this.money = money; } public void print(){ System.out.println("Person"); } } ---------------------- //If a subclass inherits from the parent class, it will have all the methods of the parent class public //Subclass public class Student extends Person { private String name = "wanhan"; public Student() { //Hidden code: the parameterless construction of the parent class was called super();//Calling the constructor of the parent class must be on the first line of the subclass constructor System.out.println("Student Nonparametric execution"); } public void test(String name){ System.out.println(name);//pengfan System.out.println(this.name);//wanhan System.out.println(super.name);//liuao } public void print(){ System.out.println("Student"); } public void test2(){ print();//Student this.print();//Student super.print();//Person } } ---------------------- //Subclass public class Teacher extends Person { } ---------------------- public class Application { public static void main(String[] args) { Student student = new Student(); student.say(); System.out.println(student.getMoney()); Person person = new Person(); person.say(); student.test("pengfan");//Run view results student.test2(); } } //After the subclass inherits from the parent class, the created object can directly call the public method in the parent class
Object class: in java, all classes inherit object directly or indirectly by default
super and this:
super Note: 1. super The constructor of the parent class must be called in the first instance of the constructor 2. super Must only appear in a subclass's method or constructor! 3. super and this Constructor cannot be called at the same time! contrast this: The objects represented are different: this:This object called by itself super:Represents a reference to a parent class object premise this:Can be used without inheritance super:Can only be used under inheritance conditions Construction method this(); Construction of this class super(); Construction of parent class!|
Method override:
rewrite: Inheritance relationship is required. The subclass overrides the method of the parent class! 1. Method names must be the same 2.The parameter list must be the same 3.Modifier :The scope can be expanded but not reduced: public>protected>default>private 4.Exception thrown:The scope can be reduced, but not expanded When overridden, the methods of the child class and the parent class must be consistent:Different methods! Why rewrite:1-Functions of parent class,Subclasses are not necessarily required.Or not necessarily satisfied! //Rewriting is the rewriting of methods and has nothing to do with properties public class B { public void test(){ System.out.println("B=>test()"); } } ------------ //Rewriting is the rewriting of methods and has nothing to do with properties public class A extends B { @Override//annotation public void test() { //super.test(); System.out.println("A=>test()"); } /* public void test(){ System.out.println("A=>test()"); } */ } ----------------- public class App { public static void main(String[] args) { A a = new A(); a.test(); //A reference to a parent class points to a child class B b = new A();//The subclass overrides the method of the parent class b.test(); } }
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 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.
-
instance of type conversion (reference type)
//Person class public class Person { public void run(){ System.out.println("run"); } } /* Precautions for polymorphism: 1, Polymorphism is the polymorphism of methods, and there is no polymorphism of attributes 2, The parent and child classes have connection type conversion exceptions! 3, Existence conditions: inheritance relationship, method needs to be rewritten, and parent class reference points to child class object Cannot override: 1.static Method, belonging to class, not instance 2.final constant 2.private method */ //Student class public class Student extends Person { @Override public void run() { System.out.println("sonrun"); } public void eat(){ System.out.println("eat"); } public void go(){ System.out.println("go"); } } //Teacher class public class Teacher extends Person { } //test public class Application { public static void main(String[] args) { /* //The actual type of an object is determined //But 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 a subclass can call are its own or inherit the methods of its parent class Student s1 = new Student(); //A parent class can point to a subclass, but cannot call methods unique to a subclass Person s2 = new Student(); s2.run();//The subclass overrides the method of the parent class and executes the method of the subclass s1.run(); //The methods that can be executed by an object mainly depend on the type on the left side of the object, which has little to do with the right side s1.eat(); //s2.eat();error //View relationships between classes 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);//false 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(student instanceof String);//Compilation error */ //Conversion between types //Parent rotor class Person stud1 = new Student(); //stud.go();// error //By converting the object of Student to Student type, we can use the method of Student type ((Student)stud1).go(); //When a subclass is converted to a parent class, some of its original methods may be lost Student stud2 = new Student(); stud2.go(); Person per1 = stud2; //per1.go();// Cannot call } } /* 1.The parent class refers to an object that points to a child class 2.Convert the child class to the parent class and transform upward 3.Convert a parent class to a child class and transform downward: Cast 4.Convenient method call, reduce code repetition, concise */
static
public class Student { private static int age = 1;//Static variable private double score = 60;//Non static variable public void run(){//Non static method } public static void go(){//Static method } public static void main(String[] args) { Student s1 = new Student(); System.out.println(Student.age); //System.out.println(Student.score); report errors System.out.println(s1.score); System.out.println(s1.age); go(); Student.go(); s1.go(); s1.run(); //Student.run();// report errors } }
//Class cannot be inherited after it is final public final class Person { { //Anonymous code block //The program cannot be called actively during execution //Automatically created when an object is created, before the constructor //It is generally used to assign initial value System.out.println("Anonymous code block"); } static { //Static code block, which is executed when the class is loaded, and is permanently loaded only once System.out.println("Static code block"); } public Person() { System.out.println("Construction method"); } public static void main(String[] args) { Person p = new Person(); Person p2 = new Person(); } }
//Static carry in package import static java.lang.Math.PI; import static java.lang.Math.random; public class Test { public static void main(String[] args) { System.out.println(random()); System.out.println(PI); } }
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.
- Abstract classes cannot use the new keyword to create objects. 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 an abstract method that the abstract class does not implement, otherwise the subclass must also be declared as an abstract class.
//abstract class public abstract class Action { //Abstract, abstract method, only method name, no method implementation! public abstract void doSomething(); /* You can't new create an abstract class. You can only implement it by subclasses Ordinary methods can be written in abstract classes Abstract methods must be in abstract classes */ public void go(){ } //Improve development efficiency } //Subclasses that inherit an abstract class must implement all methods of the abstract class unless the subclass is also an abstract class public class A extends Action { public A() { System.out.println("A Constructor for"); } @Override public void doSomething() { } }
Interface
- Common class: only concrete implementation
- Abstract classes: concrete implementations and specifications (abstract methods) are available!
- Interface: only specification!
- 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 good, you must kill the bad.
- The essence of interface is contract, just like the law between us. After making it, everyone abides by it.
- The essence of OO 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 + +, 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
//Interface public interface UserService { //Constant - pubic static final int age = 99; //All defined methods in the interface are actually Abstract public abstract void add(String name); void delete(String name); void update(String name); void query(String name); } //Interface public interface TimeService { void time(String time); } //realization public class UserServiceImp implements UserService,TimeService { //Using interface to realize multi "inheritance" @Override public void add(String name) { //code } @Override public void delete(String name) { //code } @Override public void update(String name) { //code } @Override public void query(String name) { //code } @Override public void time(String time) { //code } }
Interface: 1.Is a code constraint 2.Define some methods for different people to use 3.Methods in interfaces-public abstract 4.Constants in interface-public static final 5.Interface cannot be instantiated, there is no constructor 6.implements Multiple interfaces can be implemented 7.You must override the methods in the interface
Inner class
An internal class is to define a class within a class. For example, if a class B is defined in class A, class B is called an internal class relative to class A, and class A is an external class relative to class B.
1. Member internal class
2. Static internal class
3. Local internal class
4. Anonymous inner class
//class public class Outer { private int id=99; public void out(){ System.out.println("External class method"); } //Member inner class public class Inner{ public void in(){ System.out.println("Inner class method"); } //You can get the private properties of the external class public void getId(){ System.out.println(id); } } //Static inner class public static class Inner1{ public void in(){ System.out.println("Static inner class method"); } } //Local inner class public void method(){ class Inner2{ public void in2(){ System.out.println("Methods of local inner classes"); } } } } //There can be multiple class classes in a java class, but there can only be one public clas class A{ public static void main(String[] args) { } } //test public class Testapp { 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(); inner.getId(); //An initialization class without a name does not need to save an instance to a variable //Use of anonymous objects new Apple().eat(); new UserService(){ @Override public void hello() { System.out.println("hello"); } }; } } class Apple{ public void eat(){ System.out.println("eat"); } } interface UserService{ void hello(); }