java object oriented

object-oriented

01_ What is object oriented

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

    • Process oriented is suitable for dealing with some simple problems

  • Process oriented thought

    • 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 and analyze them 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

  • The essence of object-oriented programming is to organize code by class and data by object

  • Abstract (extract similar commonalities)

  • Three characteristics: encapsulation, inheritance and polymorphism

  • 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.

02_ Review method

Static method: a method with static added is a static method

Static methods can be called directly through class name and method name

Non static methods: methods without static

 //You need to instantiate this class new
 //Suppose there is a dog non static method in the add class, how to call it?
 add add=new add();
 //Direct call
 add.dog();

Object type object name = object value

Static methods cannot call non static methods. The same is true for non static methods.

Static methods are loaded with classes, and non static methods exist only after class instantiation.

Formal parameter is just a formal existence with theout formal value. The argument is its formal value.

03_ 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.

Example: animals, plants, mobile phones, computers

They do not refer to a specific thing

 

Objects are concrete instances of abstract concepts

Example: Zhang San is a concrete example of human beings,

It is a concrete instance rather than an abstract concept that can reflect the characteristics and show the functions.

Class is abstract and needs to be instantiated

Class instantiation will return an object of its own!

04_ constructor

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.

 //Nonparametric structure
 public Person(){}
 //Parametric structure
 public Person(String name,int age){
     this.name=name;
     this.age=age;
 }

Constructors, 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 class name

  • There must be no return value and void cannot be written

effect:

  • The essence of new is to call the constructor

  • Initializes the value of the object

Note:

  • After defining a parameterized construct, if you want to use a parameterless construct, you must define a parameterless construct

A constructor will have a method even if it doesn't write anything

 pet dog=new pet();
 pet cat=new pet();
 //cat and dog here are reference variable names. They have only one address value in the stack, and the actual data is stored in the heap

05_ Summary

  1. Classes and objects

    Class is an abstract template, and object is a concrete instance

  2. Corresponding reference

    Basic types: 8

    Reference type: objects are operated by reference. The data in the stack are address values, and the actual data is stored in the heap

  3. Property, Field, member variable

    Modifier attribute type attribute name = attribute value

  4. Object creation and use

    You must use the new keyword and constructor, Person pe=new Person();

    Object attribute: pe.name;

    Object: pe.sleep();

  5. Class composition:

    Static properties: member variables

    Dynamic behavior: Methods

06_ encapsulation

Programming should pursue "high cohesion and high 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 means that only a small amount of leakage is left 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.

Private property: get/set

Get is used to get the data set and set the value for the data

 // When set obtains data, it can detect the data. If illegal data is encountered, it can be directly screened out.
 // In the following example, the set age cannot be greater than 100 or less than 0. If it is greater than or less than the set value, the specified content will be returned
 //Class a
 private int age;
 public int getAge() {
     return age;
 }
 ​
 public void setAge(int age) {
  if (age < 100 && age > 0) {
     this.age = age;
  } else {
     System.out.println("Wrong age!");
  }
 }
 //Class b
 aa.setAge(101);   //set input value
 System.out.println(aa.getAge());   //This value is returned to the get method after passing through the parent class
 ​
 //The output result is: age error!

07_ 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", and a subclass is an extension of the parent class.

java has only single inheritance, not multiple inheritance!

Inheritance is a relationship between classes. In addition, the relationship between classes includes 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 the parent class and is represented by the keyword extends.

In a sense, there should be a "is a" relationship between the child class and the parent class.

  • object class

    All classes directly or indirectly inherit the object class

  • super

    0.super is the method and property that can call the parent class

    1. super calls the constructor of the parent class, which must be in the first instance of the constructor

    2. super must only appear in subclass methods or constructor methods.

    3. super and this cannot call constructor at the same time.

    VS this:

    1. The objects represented are different:

      this: the object of the caller itself

      super: represents a reference to a parent object

    2. Premise:

      this: can be used without inheritance

      super: can only be used in inheritance conditions

    3. Construction method:

      This: the structure of this class

      super: Construction of parent class

  • Method Override

    Rewriting requires inheritance. Subclasses override the methods of the parent class

    1. Method names must be the same

    2. The parameter list must be the same

    3. Modifier: the range can be expanded but not reduced

    4. Exceptions thrown: the range can be reduced, but not expanded;

08 polymorphism

 //Suppose Student inherits Teacher
 //There is only one method in Teacher
 public void san(){System.out.println("a");}
 //Methods in Student
 public void san() {System.out.println("b");}
 //main method of test
 public static void main (String[] args){
     Student a = new Student();
     Teacher b = new Student();
     a.san();
     b.san();
 }
  //Output results
     a
     a
  //If students and methods in Teachar add static results
     a
     b
         
  //result
  //Polymorphism is the diversity of methods. Changing static and the data type of call can output different results        
 ​

 

Precautions:

  1. Polymorphism is the polymorphism of methods, and there is no polymorphism of attributes

  2. Existence conditions: inheritance relationship, method needs to be overridden, and parent class reference points to child class object! F f1=new s();

  3. Method call error, exception will be reported, ClassCastException!

    The following methods cannot be overridden and cannot use polymorphism:

    1. static: it belongs to class, not instance

    2. final: constant, that is, it is in the constant pool and cannot be modified

    3. Private: private method, cannot be overridden

 

 //Suppose class f inherits class s
 f f=new f();
 s ff=new f();
 System.out.println(s instanceof f);
 System.out.println(s instanceof s);
 //You can judge whether it belongs to inheritance parent-child relationship
 Student s22=(Student)s2;//Method 1
 s22.sum();
 ((Student)s2).sum();//Method 2
 //This method uses forced type conversion and modifies the type of s2 from Person to Student.

characteristic:

  1. A parent class reference points to a child class object

  2. Convert the child class to the parent class and transform upward

  3. Convert a parent class to a child class and transform down: Cast

  4. Convenient method call and reduce duplicate code!

Child to parent: Transform upward, directly, and lose the unique methods that can be called directly in the subclass;

Parent rotor: if you transition down, you will lose the methods of the parent class overridden by the child class.

 

09_static keyword

Static is static. What it modifies will be loaded with the class

 {//Anonymous code block
   System.out.println(1);
 }
 static {//Static code block
   System.out.println(2);
 }
 //The output is 2
 //The static will be loaded with the class, which will be in front of the anonymous code block
 private static int age=1500;    //Static variable
 private int age1=2000;              //Non static variable
 ​
 test s1= new test();    //create object
 System.out.println(s1.age);     
 System.out.println(s1.age1);    //Objects can be output normally
 ​
 System.out.println(test.age);   //The modified variable can be output through the class name
 System.out.println(test.age1);  //If it is not decorated, it cannot be called through the class name
 ​

You can use Math.random; Import random number

 System.out.println(Math.random());
 ​
 //If you feel troublesome, you can use the static guide package
 ​
 import.static java.lang.Math.random;
 ​
 System.out.println(random());
 //This eliminates the need to write Math

10_ abstract class

The abstract modifier can be used to modify a method or a class. If a method is modified, 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.

Implementation

When implementing a method, it implements an interface or inherits an abstract class. The methods defined in the interface and the abstract class are not implemented, that is, there is no method body. You need to implement this method in the current class.

Overloading

If you override a method, it means that there is a complete method in the integrated parent class, and you do not intend to use it or need to make some modifications to achieve a certain purpose, so you need to override it. It is common to override the toString() method in Object

In short, those with a method body are called rewriting, and those without a method body are called implementation.

 

11_ Interface

1, What is the interface?

Interfaces are abstractions (abstract classes are concrete abstractions).

For example, to make a sports watch, the interface is the function that the product needs to realize. I want to realize the combination of this watch with APP, the reminder of incoming calls, the setting of alarm, the real-time monitoring of heart rate and the recording of steps... I won't tell you any specific implementation method. I will only give you a framework of product functions. If you are a member of my team, you want to make this sports watch, Then you must implement all the contents defined by me.

That is, "if you are..., you must..."

This is the interface. In a program, it is equivalent to the behavior specification of a class.

 

Interface class name and Implementation: Impl is usually added after the interface class name to represent the implementation of this interface class

2, What is the function of the interface?

  1. Code specification

  2. It is conducive to code maintenance

  3. It is conducive to the security and tightness of the code

  4. It enriches the way of inheritance

3, Interface syntax

 //Interface declaration
 ​
 //Keywords: interface
 public interface  Interface name {}
 ​
 //Interface body
 1. Constant (no variable)  
 ( public static final ) int MAX = 100; Can be omitted public static final
 ​
 2. Abstract method
 (public abstract) void add();Can be omitted public abstract
 ​
 Both constants and abstract methods have only one access modifier: public
 ​
 The interface is provided by default  public,static,final,abstract keyword

Implementation of interface

 keyword: implements
 ​
 1. Class can implement one or more interfaces
 public class Doglmpl implements Dog,Sleepable
 ​
 Dog You can also inherit a concrete class    
 public class Doglmpl extends  Animal implements Dog, Sleepable
 ​
 2. All methods in the interface must be implemented in the class (abstract classes can only implement some methods in the interface)
 ​
 3. Class, the access modifier must be  public
     
 4. Constants defined in the interface can be used directly in classes that inherit the interface.
 ​
 5. Interface can implement pseudo multi inheritance
 ​
 6. An interface cannot be instantiated. It does not have its own implementation and construction methods, only abstract methods
 Inheritance between interfaces 
     public interface A{}
     public interface B extends A{}      
 // A inherited from interface B

Summary:

  1. An interface is a specification

  2. Interface declaration: public interface a{}

  3. Interface inheritance uses the implements keyword. Interfaces can implement multiple inheritance:

    public class A implements B,C {}

  4. All methods of the interface must be overridden in the implementation class

  5. Interfaces can inherit interfaces

 

12_ Inner class

An internal class is to define another class in a class. For example, if a class b is defined in class A, then a is the external class and b is the internal class.

1. There are four internal classes:

  1. Member inner class

     public  class Outer {
         private int id=10;
         public void out(){
             System.out.println("This is an external class");
         }
         
         public class Inner {
             public void in(){
                 System.out.println("This is an inner class");
             }
             public void getID(){
                 //The inner class can call the private properties of the outer class
                 System.out.println(id);
             }
         }
     }
  2. Static inner class

    A class decorated with static is called a static inner class. It cannot use the properties and methods of an outer class

  3. Local inner class

     class B{
         public void eat(){
             //Local inner class, the class in which the method is redefined
             class b{
             }}}
  4. Anonymous Inner Class

     public class test {
         public static void main(String[] args) {
     //Anonymous internal class, no name initialization class, no need to save the instance in the variable
             new a().eat();
         }
     }
     class a{
         public void eat(){
             System.out.println("1");
         }
     }
  5.  

Added by Mr.Shawn on Sun, 28 Nov 2021 19:03:36 +0200