Java object oriented

Process oriented & object oriented

Process oriented thought

The steps are clear and simple, what to do in the first step, what to do in the second step

Facing the process is suitable for dealing with some simpler problems

Object 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 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 by class and data by object.

abstract

Three characteristics:

​ 1. encapsulation

​ 2. inherit

​ 3. 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.

Review methods and deepening

Definition of method

Modifier

Return type

break: jump out of the switch and end the loop. It is different from return

Method name

parameter list

Exception throw

Method call

Static method

Non static method

Formal and argument

Value passing and reference passing

this keyword

package com.oop;

import java.io.IOException;

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

    }
/*
*       Modifier return value type method name (...) {
*     //Method body
*       return Return value;
* }
*
* */
    public String sayHello(){
        return "hello,world";
    }
    public void print(){
        return;
    }
    public int max(int a,int b){
        return a>b ? a : b;//Ternary operation
    }
    //Array subscript out of bounds Arrayindexoutofbounds
    public void readFile(String file)throws IOException{
        
    }
}
package com.oop;

public class Demo02 {
    public static void main(String[] args) {
        //Instantiate this class
        //Object type object name = object value
        Student student = new Student();
        student.say();
    }
    //static is loaded with the class
    public static void a(){
      //  b();
    }
    //Class does not exist until it is instantiated
    public void b(){

    }
}
package com.oop;
//Student class
public class Student {
    //Non static method
    public void say(){
        System.out.println("The student spoke");
    }
}
package com.oop;

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

    }
    public static int add(int a,int b){
        return a+b;
    }
}
package com.oop;
//pass by value
public class Demo04 {
    public static void main(String[] args) {
        int a = 1;
        System.out.println(a);//1
        Demo04.change(a);
        System.out.println(a);//1

    }
    //The return value is null
    public static void change(int a){
        a = 10;
    }
}
package com.oop;
//Reference passing: object, essence or value passing
public class Demo05 {
    public static void main(String[] args) {
        Perosn perosn = new Perosn();
        System.out.println(perosn.name);//null
        Demo05.change(perosn);
        System.out.println(perosn.name);

    }
    public static void change(Perosn perosn){
        perosn.name = "Bengal black";
    }
}
//Defines a Perosn class with an attribute: name
class Perosn{
    String name;//null
}

Relationship between class and object

Class is an abstract data type. It is the 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 - class of specific things

Objects are concrete instances of abstract concepts

Zhang San is a concrete example of man, and Wang CAI in Zhang 3's family is a concrete example of dog.

What can embody the characteristics and functions is a concrete example, not an abstract concept

We can convert these ideas into code implementation!

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.

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

Constructors must master

package com.oop.demo02;
//Student class
public class Student {
    //Properties: Fields
    String name;
    int age;
    //method
    public void study(){
        System.out.println(this.name+"I'm learning");
    }


}
package com.oop.demo02;
//A project should have only one main method
public class Application {
    public static void main(String[] args) {
        //Class: abstract, instantiated
        //Class will return its own object after instantiation
        //A student object is a concrete instance of a student class
        Student xm = new Student();
        Student xh = new Student();

        xm.name = "Xiao Ming";
        xm.age = 19;

        System.out.println(xm.name);
        System.out.println(xm.age);

        xh.name = "Xiao Hong";
        xh.age = 19;

        System.out.println(xh.name);
        System.out.println(xh.age);

    }
}
package com.oop.demo02;
//java--->class
public class Person {
    //A class will have a method even if it doesn't write anything
    //Display definition constructor
    String name;
    //Instantiation initial value
    //1. Using the new keyword is essentially calling the constructor
    //2. Used to initialize values
    public Person(){
        this.name = "Bengal black";
    }
    //Parameterized Construction: once a parameterized construction is defined, no parameters must be explicitly defined
    public Person(String name){
        this.name = name;

    }
}
  /*  public static void main(String[] args) {
        //new Instantiated an object
        Person person = new Person("mengjialahei");

        System.out.println(person.name);

    }
    Constructor:
    1.Same as class name
    2.no return value
    effect:
    1.new The essence is to call the constructor
    2.Initializes the value of the object
    Note:
    After defining a parameterized construct, if you want to use a parameterless construct, you can define a parameterless construct
    Alt+insert
    
    */
package com.oop.demo03;

public class Pet {
    public String name;
    public int age;
    //Nonparametric structure
    public void shout(){
        System.out.println("Let out a cry");
    }
    public static void main(String[] args) {
        Pet dog = new Pet();
        dog.name="Woof, woof";
        dog.age=5;
        dog.shout();
        System.out.println(dog.name);
        System.out.println(dog.age);
    }
}

Summary

* 1.Classes and objects
* A class is a template: an abstract object is a concrete instance
* 2.method
* Define call
* 3.Corresponding reference
* Reference type: basic type (8)
* Objects are manipulated by reference: stacks----->heap
* 4.Properties: Fields Field Member variable
* Default initialization:
* Number: 0.0
* char: u0000
* boolean: false
* quote: null
* Modifier property type property name=Attribute value
* 5.Object creation and use
* Must use new Keyword creation object, constructor Person mengjialahei = new Person();
* Object properties mengjialahei.name
* Object method mengjialahei.sleep()
* 6.Class:
* Static properties
* Dynamic behavior
* 7.Encapsulation inheritance polymorphism

encapsulation

The dew that should be exposed, the hide that should be hidden

Our program design should pursue * * "high cohesion, low coupling" * *. High cohesion means that the internal data operation details of the class are completed by ourselves, and external interference is not allowed; low coupling: only a small number 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

package com.oop.demo04;
//Class private: private
public class Student {
    private String name;//name
    private int id;//Student number
    private char sex;//Gender
    private int age;

    //Provide some methods that can manipulate this property
    //Provide some pulic get and set methods
    //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;
    }
//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>120 || age<0){
            this.age = 3;
        }else {
            this.age = age;
        }

    }
}
/*
* 1.Improve program security
* 2.Implementation details of hidden code
* 3.Unified interface
* 4.System maintainability increased
* */
public class Application {
    public static void main(String[] args) {
        Student s1 = new Student();
        s1.setName("Bengal black");
        System.out.println(s1.getName());
        s1.setAge(555);
        System.out.println(s1.getAge());

    }

}

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

In JAVA, there is only inheritance, not much inheritance

Inheritance is a kind of relationship between a class and the same class, including dependency, combination, 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 missing key word extends.

In a sense, there should be a relationship of "is a" between child classes and parent classes

object class

super

Method rewrite

package com.oop.demo05;
//In JAVA, all classes inherit Object directly or indirectly by default
//Person is: parent class
public class Person {
    //public
    //protected
    //default
    //private
    public void say(){
        System.out.println("Hello hello");
    }
}



package com.oop.demo05;
//Student is: subclass of derived class
//If a subclass inherits from the parent class, it will have all the methods of the parent class
public class Student extends Person{
    //ctrl+h inheritance diagram
    /*
     * 1.Improve program security
     * 2.Implementation details of hidden code
     * 3.Unified interface
     * 4.System maintainability increased
     * */
    public static void main(String[] args) {
        Student student = new Student();
        student.say();
    }
}


package com.oop.demo05;
//Teacher is: subclass of derived class
public class Teacher extends Person{
}
package com.oop.demo05;
//In JAVA, all classes inherit Object directly or indirectly by default
//Person is: parent class
public class Person {
 public Person() {
  System.out.println("Person Nonparametric execution");
 }

 protected String name = "mengjialahei";
 //Private things cannot be inherited
 public void print(){
  System.out.println("Person");
 }
    

}


package com.oop.demo05;
//Student is: subclass of derived class
//If a subclass inherits from the parent class, it will have all the methods of the parent class
public class Student extends Person{
    public Student() {
        System.out.println("Student Nonparametric execution");
    }

    private String name = "mjlh";
    public void print(){
        System.out.println("Student");
    }
    public void test1(){
        print();
        this.print();
        super.print();
    }
  public void test(String name){
      System.out.println(name);//Bengal black
      System.out.println(this.name);//mjlh
      System.out.println(super.name);//mengjialahei
  }

}

package com.oop;

import com.oop.demo05.Student;

public class Application {
    public static void main(String[] args) {
        Student student = new Student();
       // student.test("Bangladesh black");
        //student.test1();

    }

}

package com.oop.demo05;

public class A extends B{
    public static void test(){
        System.out.println("A=>test()");
    }
}


package com.oop.demo05;
//Rewriting is the rewriting of methods and has nothing to do with properties
public class B {
    public static void test(){
        System.out.println("B=>test()");
    }
}


package com.oop;
import com.oop.demo05.A;
import com.oop.demo05.B;
public class Application {
    //Static methods are very different from non static methods
    //Static method: the method call is only related to the data type defined on the left
    //Non static: overriding
    public static void main(String[] args) {
        A a = new A();
        a.test();//A
        //A reference to a parent class points to a child class
        B b = new B();
        b.test();//B
    }
}

super note:
1.super must call the constructor of the parent class in the first instance of the constructor
2.super must only appear in subclass methods or constructor methods
3.super and this cannot call the 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 in inherited conditions
Construction method
this(); Construction of this class
super(); Construction of parent class
Override: inheritance relationship is required. The subclass overrides the method of the parent class
1. The method name must be the same
2. The parameter list must be the same
3. Modifier: the scope can be expanded public > protected > Default > private
4. Exception thrown: the range can be narrowed, but cannot be expanded. ClassNotFoundException – > exception (large)
The method of overriding a subclass must be the same as the parent class, and the method body must be different
Why rewrite:
1. The function of the parent class and the subclass do not have to be required or satisfied
Alt+Insert;Override

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

instanceof

package com.oop.demo06;

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.Type conversion exception ClassCastException associated with parent and child classes
 3.Existence condition: inheritance relationship, method needs to be overridden. The parent class reference points to the child class object Father f1 = new Son();
 
 Cannot override
 1.static method. Belongs to class, it does not belong to instance
 2.final constant
 3.private method
 */
 
 package com.oop.demo06;

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


package com.oop;

import com.oop.demo06.Person;
import com.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 students can call are their own or inherit the parent class
        Student s1 = new Student();
        //The Person parent type can point to subclasses, but cannot call methods unique to subclasses
        Person s2 = new Student();
        Object s3 = new Student();
        //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
        s2.run();//The subclass overrides the method of the parent class and executes the method of the subclass
        s1.run();
        ((Student) s2).eat();//Cast type
        s1.eat();
    }

}

package com.oop;

import com.oop.demo06.Person;
import com.oop.demo06.Student;

public class Application {
    public static void main(String[] args) {
        //Conversion between types: parent and child classes
        //High and low
        Person obj = new Student();
        //Student converts this object to student type, and we can use the method of student type
        Student student = (Student) obj;
        student.go();
    }

}
/*
1.The parent class refers to an object that points to a child class
2.Convert a child class to a parent class and transform upward
3.Convert a parent class to a child class and cast it downward
4.Facilitate method calls and reduce duplicate code

*/


package com.oop.demo06;

public class Student extends Person{
public void go(){
    System.out.println("go");
}
}
/*
public static void main(String[] args) {
        //Object>Teacher
        //Object>Person>Teacher
        //Object>Person>Student
        Object object = new Student();
       // System.out.println(X instanceof Y);//Can it be compiled
        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

    }

*/
package com.oop.demo07;
//static
public class Student {
    private static int age;//Static variable multithreading
    private double score;//Non static variable
    public void run(){


    }
    public static void go(){

    }

    public static void main(String[] args) {
        go();
    }
}



package com.oop.demo07;

public class Person {
    //2
    {
        //Code block (anonymous code block)
        System.out.println("Anonymous code block");
    }
    //1: Execute only once
    static {
        //Static code block
        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();
    }
}


package com.oop.demo07;
//Static package import
import static java.lang.Math.random;
import static java.lang.Math.PI;
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 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.

package com.oop.demo08;
//Abstract abstract class: class extensions: single inheritance (interfaces can inherit more than one)
public abstract class Action {
    //Constraint someone to help us achieve
    //Abstract abstract abstract method has only method name and no method implementation
    public abstract void doSomething();
    //1. You cannot use the abstract class new. You can only rely on subclasses to implement its constraints
    //2. Ordinary methods can be written in abstract classes
    //3. Abstract methods must be in abstract classes
    //4. Abstract constraints
}


package com.oop.demo08;

public class A extends Action{
    @Override
    public void doSomething() {

    }
}

Interface

Common class: only concrete implementation

Abstract classes: concrete implementations and specifications (abstract methods) are available!

Interface: only specification! I can't write my own method~

"Interface is a specification, which defines a set of rules, reflecting the idea of" if you... You must be able to... "In the real world. If you are an angel,

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 abides by it.

00 is the abstraction of objects, which can be best reflected in the interface. Why do we discuss design patterns only for those with abstraction

The language of capability (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

package com.oop.demo09;
//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
//Multiple inheritance uses interfaces to implement multiple inheritance
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() {
        
    }
}

package com.oop.demo09;
//Interface defines keywords, and the interface needs to have implementation classes
public interface UserService {
    //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);
}

package com.oop.demo09;

public interface TimeService {
    void timer();
}

effect:
    1.constraint
    2.Define some methods for different people to implement
    3.The methods are public abstract
    4.Constants are public static final
    5.The interface cannot be instantiated. There is no constructor in the interface
    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

package com.oop.demo10;

public class Outer {
    private int id=100;
    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 com.oop;

import com.oop.demo10.Outer;

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


}


Human realization
3. All methods are public abstract
4. Constants are public static final
5. The interface cannot be instantiated. There is no constructor in the interface
6.implements can implement multiple interfaces
7. The method in the interface must be rewritten

### Inner class

An inner class is a class defined inside a class, For example, A Class B class,that B Class relative A Class is called an inner class,and A Class relative B Class is an external class.

1.Member inner class

2.Static inner class

3.Local inner class

4.Anonymous Inner Class 

```bath
package com.oop.demo10;

public class Outer {
    private int id=100;
    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 com.oop;

import com.oop.demo10.Outer;

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


}


Keywords: Java

Added by H4mm3r3r on Sun, 16 Jan 2022 01:47:12 +0200