Object-Oriented Programming OOP

Object-Oriented Programming OOP

What is Object Oriented

Object-oriented definitions:

Classified way of thinking

The design of dividing programs into blocks and functions

First think about these categories separately, then process-oriented think about the details under each category

Finally, in combination, it's ideal for handling loads and issues that require multiple people to work together

For describing complex things, in order to grasp macroscopically and analyze reasonably as a whole, we need to use object-oriented thinking to analyze the whole system. However, specific to micro-operation, process-oriented thinking is still needed to deal with

Object-oriented nature:

Organize code as classes, organize (encapsulate) data as objects

Abstract concepts

Pull out the common points of the objects. Both cats and tigers are cats, similar to

Three characteristics

  1. encapsulation

    Encapsulate the object with only one interface

  2. inherit

    Subclasses inherit and extend from the parent class, with the excuse and method of the parent class

  3. polymorphic

Note:

  1. From an epistemological point of view, first there are objects, then classes. Objects are concrete things. Classes are abstract and are abstract from objects
  2. From the code run point of view, there are classes before objects. Classes are templates for objects

Definition of Retrospective Method

The code snippet is as follows:

//Demo01 Class
public class Demo01 {
    //    main method
    public static void main(String[] args) {

    }

    /*
     * Modifier Return Value Type Method Name (...) {
     *       //Method Body
     *          return Return value
     * */
//    return end method, returns a result
    public String sayHello() {
        return "hello,world";
    }

    public int max(int a, int b) {
        return a > b ? a : b;//Ternary operator
    }

//    Array subscript out of bounds: Arrayindexoutofbounds
    public void readFile(String file) throws IOException{

    }
}

Review method calls

The code fragmentation is as follows:

public class Demo02 {
    public static void main(String[] args) {
        Student.say();
//        Instantiate this class new
//        Object type object name = object value;
        Student student = new Student();
        student.says();
    }

//    Static is loaded with the class, so static methods cannot call non-static methods
//    Nonstatic method class exists after instantiation
}

public class Demo03 {
    public static void main(String[] args) {
//        The types of actual and formal parameters should correspond!
        int add = Demo03.add(1, 2);
        System.out.println(add);
    }

    public static int add(int a,int b){
        return a+b;
    }
}

Reference and value passing

public class Demo04 {
    public static void main(String[] args) {
        int a =1;
        System.out.println(a);
        Demo04.change(a);
        System.out.println(a);  //Output result is 1
    }
//    Return value is empty
    public static void change(int a){
        a =10;
    }
}


//Reference Passing: Object, Essential or Value Passing
public class Demo05 {
    public static void main(String[] args) {
        Person person = new Person();
        System.out.println(person.name);//null
        Demo05.change(person);
        System.out.println(person.name);//Qin Xinjiang
    }
    public static void change(Person person){
//        Person is an object: pointing to --> Person person = new Person(); This is a specific person who can change attributes
        person.name="Qin Xinjiang";
    }
}


//A Person class is defined with one attribute:name
class Person{
    String name;//null
}

Relationship between Classes and Objects

The code snippet is as follows:

There are two classes, one is the startup class and the other is the student class.

//Student Class
public class Student {
//    Attribute: Field
    String name;//null
    int age;//0

//    Method
    public void study(){
        System.out.println(this.name+"I'm learning");
    }
}
//Good program? Model the world better!

//Startup Class
//A project should have only one main method
public class Application {
    public static void main(String[] args) {
//        Class: abstract, instantiated
//        A class instantiates and returns its own object!
//        The Student object is a concrete instance of the Student class!

        Student xiaoming = new Student();
        Student xh = new Student();

        xiaoming.name ="Xiao Ming";
        xiaoming.age =3;
        System.out.println(xiaoming.name);
        System.out.println(xiaoming.age);

        xh.name ="Little Red";
        xh.age =3;
        System.out.println(xh.name);
        System.out.println(xh.age);
    }
}

Constructor Details

The code snippet is as follows:

public class Person {
//        A class has a method (default constructor) even if it doesn't write anything.
//    Display defines constructors
    String name;
//    Instantiate Initial Value
//    1. Using the new keyword is essentially calling the constructor
//    2. Used to initialize values
    public Person(){
        this.name ="qinjiang";
    }

//    Parametric constructs: once a parametric construct is defined, a definition must be displayed without a parameter
    public Person(String name){
        this.name =name;
    }
//    command+n can generate constructors with shortcuts
}


/*
public class Application {
    public static void main(String[] args) {
//        new Instantiate an object
        Person person = new Person();
        System.out.println(person.name);//qinjiang
    }
}


    Constructor:
        1.Same as class name
        2.no return value
    Effect:
        1.new Essentially calling a construction method
        2.Initialize the value of the object
    Note:
        1.Parametric constructs: once a parametric construct is defined, a definition must be displayed without a parameter
* */

Create Object Memory Analysis

The code snippet is as follows:

//Memory Analysis Case
public class Pet {
    String name;
    int age;
//    Parametric construction
    public void shout(){
        System.out.println("Gave a call");
    }
}

/*      
public class Application {
    public static void main(String[] args) {
        Pet dog =new Pet();
        dog.name =""Prosperous wealth";
        dog.age= 3;
        dog.shout();
        System.out.println(dog.name);
        System.out.println(dog.age);
    }
}

* */

Memory analysis drawing example:

Simple summary classes and objects

The code snippet is as follows:

public class Application {
    public static void main(String[] args) {
        /*
        * 1.Classes and Objects
        *   Class 11 template: abstract, object is a specific instance
        * 2.Method
        *   Define, call!
        *
        * 3.Corresponding reference
        *   Reference type: Basic type (8)
        *     Objects are manipulated by reference: stack--->stack
        * 4.Attribute: Field Field Field member variable
        *   Default initialization:
        *       Number: 0.0
        *       char:    u0000
        *       boolean: false
        *       Reference: null
        *   Modifier Attribute Type Attribute Name=Attribute Value!
        *
        * 5.Creation and use of objects
        *   -Objects must be created using the new key child, constructor Person kuangshen =new Person();
        *   -The object's attribute kuangshen.name
        *   -Object's method kuangshen.sleep()
        *
        * 6.Class:
        * Static Properties
        * Dynamic Behavior*/
    }
}

encapsulation

The dew of the dew, the hide of the hide

( Our program design pursues "high cohesion, low coupling" and high cohesion, which means that the internal data operation details of the class are completed by itself, and external interference is not allowed. Low coupling: Expose only a small number of methods for external use

Encapsulation (data hiding)

( Generally, direct access to the actual representation of data in an object should be prohibited, but accessed through an operational interface, known as information hiding

Remember this sentence: property is private, get/set

The code snippet is as follows:

//Class private:private
public class Student {

    //    Property Private
    private String name;//    Name
    private int id;//    School Number
    private char sex;//    Gender
    private int age;
//    Provide some ways to manipulate this property!
//    Provide some get and set methods for public s

    //    get gets this data
    public String getName() {
        return this.name;
    }

    //    set 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;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        if (age > 120 || age < 0) {//Wrongful
            age = 3;
        } else {
            this.age = age;
        }

    }
}

/*
public class Application {
    public static void main(String[] args) {
        Student student = new Student();
        student.setName(""Qin Xinjiang";
        System.out.println(student.getName());

        student.setAge(999);//Illegal
        System.out.println(student.getAge());
    }

}
* */

inherit

Inheritance is a relationship between classes and classes. In addition, there are dependencies, combinations, aggregations, and so on. Two classes of inheritance relationship, one is a subclass (derived class) and the other is a parent class (base class). The subclass inherits the parent class and is represented by the keyword extends. There should be a "is a" relationship in the sense between the child and the parent

The code snippet is as follows:

Parent Class:

//In java, all classes inherit Object directly or indirectly by default
//Person: Parent
public class Person /*extends Object*/{

//    public
//    protected
//    default
//    private cannot inherit
    private int money = 10_0000_0000;
    public void say(){
        System.out.println("A sentence was said");
    }

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }
}

Subclass:

//Student is: derived class, subclass
//    If a child inherits the parent class, it will have all its methods
public class Student extends Person {
//    control+h View Parent-Child Class Relationships
}

//Teacher is derived class, subclass
public class Teacher extends Person {
}

Super Details

Super Notes:

  1. super calls the parent class's constructor, which must be first in the constructor
  2. super must only appear in methods or constructors of subclasses!
  3. super and this cannot call the construction method at the same time!

Vs this:

The objects represented are different:

	1. this: Itself caller this object
	2. super: Application representing parent object

premise

  1. this: can be used without inheritance
  2. super: can only be used under inheritance conditions

Construction method

  1. This (): Construction of this class
  2. super(): the construction of the parent class!

The code snippet is as follows:

Person parent class:

//In java, all classes inherit Object directly or indirectly by default
//Person: Parent
public class Person /*extends Object*/ {
    public Person(){
        System.out.println("Person No parameters executed");
    }
    protected String name = "kuangshen";

    //    Private things cannot be inherited!
    public void print() {
        System.out.println("Person");
    }
}

Student subclass:

//Student is: derived class, subclass
//    If a child inherits the parent class, it will have all its methods
public class Student extends Person {

    public Student(){
//        Hidden code: parameterless construction of parent class called
        super();//Calling the parent class's constructor must be on the first line of the child class's constructor
        System.out.println("Student No parameters executed");
    }
    private String name ="qingjiang";
    public void print(){
        System.out.println("Student");
    }
    public void test1(){
        print();//Student
        this.print();//Student
        super.print();//Person
    }
    public void test(String name){
        System.out.println(name);//Qin Xinjiang
        System.out.println(this.name);//qingjiang
        System.out.println(super.name);//kuangshen
    }
}

override

Override definition:

Need inheritance, subclass overrides parent class's method!

  1. Method names must be the same
  2. Parameter list must be the same
  3. Modifier: Range can be expanded: pubile>Protected>Default>private (within parent inheritance, if the parent method is proteced, inheritance can be changed to pubilc, but not private)
  4. Exceptions thrown: Range can be reduced but not expanded; ClassNotFoundException-->Exception (large)

Override, the method of the subclass must be the same as the parent class, and the body of the method is different!

Why rewrite:

  1. The functions of the parent class, subclasses are not necessarily required or satisfied!
  2. conmmand+ n;override;

Code snippet:

Console:

public class Application {

    //    Static and non-static methods differ greatly!
//          Static methods: //Method calls are only on the left, with data types defined
//          Non-static: Override
    public static void main(String[] args) {

        A a = new A();
        a.test();//A
//      References to parent classes point to subclasses of classes, transition up
        B b = new A();//Subclass overrides parent's method
        b.test();//B
    }
}

Subclass A:

//inherit
public class A extends B{
//    Override Rewrite
    @Override//Note: Functional notes!
    public void test() {
        System.out.println("A=>test()");
    }
}

Parent Class B:

//Overrides are overrides of methods, not properties
public class B {
    public  void test(){
        System.out.println("B=>test()");
    }
}

polymorphic

Definition of polymorphism:

That is, the same method can adopt different behaviors depending on the sending object

The actual type of an object is determined, but there are many types of references that can point to the object

Matters needing attention:

  1. Polymorphism is the method's polymorphism, and attributes have no polymorphism
  2. Parent and child classes, linked Type conversion exception! ClassCastException!!
  3. There are conditions: inheritance relationships, methods need to be overridden, parent references point to subclass objects, methods of both types execute subclasses, Father f1=new Son();
    1. Static method, class, it's not instance hungry
    2. fianl constant
    3. private method

Conditions for the existence of polymorphisms:

  1. Inheritance
  2. Subclass overrides parent method
  3. Parent Reference Points to Subclass Object

code snippet

Parent Class:

public class Person {

    public void run() {
        System.out.println("run");
    }
}


Subclass:

public class Student extends Person {
    @Override
    public void run() {
        System.out.println("son");
    }

    public void eat() {
        System.out.println("eat");
    }
}

Console

public class Application {
    public static void main(String[] args) {
//        The actual type of an object is deterministic
//        new Student();
//        new Person();

//        The type of reference that can be pointed to is uncertain: references to parent classes point to subclasses
//          The methods that Student can call are either its own or inherit from its parent class
        Student s1 = new Student();
//        Person parent type, which can point to subclasses, but cannot call methods unique to subclasses
        Person s2 = new Student();
        Object s3 = new Student();
//        Which methods an object can execute depends on the type on the left side of the object, which has little to do with the right side!
        s2.run();//Subclasses override parent class methods and execute subclass methods
        s1.run();
    }
}

instanceof and type conversion

As long as there is an inheritance relationship between the preceding reference type and the subsequent comparison, no error will be reported. Then the inheritance relationship and the subsequent comparison will return true if they are linear, and false if they are not.

Code for instanceof:

public class Application {
    public static void main(String[] args) {
//        Object>String
//        Object>Person>Teacher
//        Object>Person>Student
        Object object = new Student();

//        System. Out. Println (x instanceof y); // Can I compile it? See if there's a relationship between x and y
        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 instance of String);// Compilation error! The two have nothing to do with each other
        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 instance of Teacher);// Compile Error
//        System. Out. Println (student instance of String); // Compile Error

    }
}

Type conversion:

  1. Parent references objects pointing to subclasses
  2. Convert subclasses into parent classes, transition up
  3. Convert parent to child, transition down, cast
  4. Convenient method calls, reduce duplicate code!

Code snippet:

public class Application {
    public static void main(String[] args) {
//        Conversion between types: parent and child
//        High and low
        Person obj = new Student();

//        Student converts this object to Student type, so we can use Student type methods! Whether to look at the front or not at the back after all

        Student obj1 = (Student) obj;
        obj1.go();
        //        Converting a subclass to a parent may lose some of its original methods
        Student student = new Student();
        Person person = student;
    }
}

static keyword details

staitc is a subordinate class and can only be executed once, with similar files

Class is terminated after final

Static properties and methods:

The code block is as follows:

//static:
public class Student {

    private static int age;//Static variable multithreaded!
    private double score;//Non-static variable

    public void run(){

    }
    public static void go(){

    }

    public static void main(String[] args) {
//        Static Properties
        Student s1 = new Student();
        System.out.println(Student.age);
        System.out.println(s1.age);
        System.out.println(s1.score);
//        Static method
        new Student().run();
        Student.go();

    }
}

Code block and static code block:

The code snippet is as follows:

public class Person {
    /*
    {
//        Code Block (Anonymous Code Block)
    }
    static {
//        Static Code Block
    }
    */
//    Example
//    2: Attach initial value~
    {
        System.out.println("Anonymous Code Block");
    }
//    1:Execute only once
    static {
        System.out.println("Static Code Block");
    }
//    3
    public Person(){
        System.out.println("Construction method");
    }

    public static void main(String[] args) {
        Person person1 = new Person();
        System.out.println("============");
        Person person2 = new Person();
    }
}

Static import package:

The code snippet is as follows:

//Static Import Package~
import static java.lang.Math.PI;
import static java.lang.Math.random;
/**
 * @author Amuese
 * @create 2021-02-15-1:48 p.m.
 */
public class Test {
    public static void main(String[] args) {
//        You do not need to add Math if you have static import packages. Yes
        System.out.println(random());
        System.out.println(PI);
    }
}

abstract class

The code snippet is as follows:

//Abstract abstract class: class extends: single inheritance-interface can inherit multiple sockets-
public abstract class Action {
//    Constraint~Someone helps us achieve it~
//    abstract, abstract method, only method name, no method implementation!
    public abstract void doSomething();
//    1. This abstract class cannot be new, it can only be implemented by subclasses: constraints!
//    2. Common methods can be written in abstract classes
//    3. Abstract methods must be in abstract classes~
//    Abstract abstraction: constraints

//    Think questions? new, is there a constructor?
//    Abstract class, abstract the meaning of existence to improve development efficiency
}

//All methods of an abstract class, which inherit its subclasses, must implement its methods unless its subclasses are also abstract
public class A extends Action {
    @Override
    public void doSomething() {

    }
}

Definition and implementation of interface

Common class: only concrete implementation

Abstract Class: Both concrete implementations and specifications (abstract methods)!

Interface: Specification only! I can't write method - professional constraints! Separation of constraints and implementation: Interface-oriented programming~

The function of the interface:

  1. constraint
  2. Define some methods for different people to implement ~10 --> 1
  3. public absrtact
  4. Public static final
  5. Interface cannot be instantiated to, there is no construction method in the interface~
  6. Implements implement multiple interfaces
  7. Methods in interfaces must be overridden~

The code snippet is as follows:

Interface:

//Abstract thinking ~Java architect ~
//Keyword defined by interface, interface needs to have implementation class
public interface UserService {
//      Constant~public static final
    int AGE =99;
    //    All definitions in an interface are actually Abstract public Abstracts
    void add(String name);
    void delete(String name);
    void update(String name);
    void query(String name);
}

public interface TimeService {
    void timer();
}

Classes that implement interfaces:

//Abstract class: extends~
//Class implements interface implements interface
//    Classes that implement class interfaces need to override methods in the interface~
//    Multiple Inheritance - Multiple Inheritance through Interfaces
public class UerServiceImpl implements UserService,TimeService {
    @Override
    public void timer() {

    }

    @Override
    public void add(String name) {

    }

    @Override
    public void delete(String name) {

    }

    @Override
    public void update(String name) {

    }

    @Override
    public void query(String name) {

    }
}

Internal Class

Definition:

Internal classes define a class inside a class, for example, class A defines a class B, then class B is called internal class relative to class A, and class A is external class relative to class B.

Types of internal classes

  1. Member Inner Class
  2. Static Internal Class
  3. Local Internal Class
  4. Anonymous Inner Class

The code snippet is as follows:

Outer class:

public class Outer {
    private int id=10;
    public void out(){
        System.out.println("This is a method of an external class");
    }
    public  class Inner{
        public void in(){
            System.out.println("This is the method of the internal class");
        }
//        Get the private properties of the external class~
        public void getID(){
            System.out.println(id);
        }
    }
//    Local Internal Class
    public void method(){
        class Inner{
            public void in(){}
        }
    }
}
//There can be more than one class class in a java class, but only one public class
class A{

}


Test class

public class Test {
//    No name initialization class
    public static void main(String[] args) {

//        Initialize class without name, do not save instance to variable~
        new Apple().eat();
        UserService userService = new UserService() {
            @Override
            public void hello() {

            }
        };
    }
}
class Apple{
    public void eat(){
        System.out.println("1");
    }
}
interface UserService{
    void hello();
}

Console

public class Application {
    public static void main(String[] args) {
//        new
        Outer outer = new Outer();
//        Instantiate the internal class through this external class~
        Outer.Inner inner = outer.new Inner();
        inner.in();
    }
}

Tags: JavaSE

Posted by chanw1 on Tue, 19 Apr 2022 01:53:41 +0930