Java Object-Oriented Programming

object-oriented programming

With a categorized thinking model, think about what classifications are needed to solve the problem first, then think about them separately, and finally think about the details of a classification process-oriented

Suitable for complex and multi-person collaboration problems

In the face of complex things, in order to grasp macroscopically and analyze reasonably as a whole, the whole system needs to be analyzed with object-oriented thinking. However, the process-oriented processing is still required for the peripheral operation.

Essentially, code is organized as classes and data is organized (encapsulated) by objects

Three main features:

  • encapsulation
  • inherit
  • polymorphic

From the point of view of code running, there are classes before objects, and classes are templates for objects

Definition of method

Static method: static

public static void main(String[] args){
    Student.say;//Error without static
    //To call a non-static method, you need to instantiate the class
    //Object type object name = object value;
    Student student = new Student();
    student.say();
    
}

Non-static method: no static

public class Student{
	public void say(){
    	System.out.println("Student talk");
	}
}

Parameter Arguments

public static void main(String[] args) {
        //The type of parameter argument is opposed
        int add = new test6().add(12,23);//This is an argument and does exist when called
        System.out.print(add);
    }
    //Parameter Arguments
    public int add(int a,int b){//Here A and B are parameters, and only when this method is called does a and B exist
        return a+b;
    }

pass by value

public static void main(String[] args) {
        int a = 1;
        System.out.println(a);//1

        test6.change(a);
        System.out.println(a);//Here the output remains 1 because java is value passed
    }

    public static void change(int a){
        a = 10;
    }

Reference Passing

	public static void main(String[] args) {
        Person person = new Person();
        System.out.println(person.name);//null
        test6.change(person);
        System.out.println(person.name);//nwt
    }

    public static void change(Person person){//Here we assign the name value to the name in the Person class, so the output is nwt
        person.name = "nwt";
    }

public class Person {
    String name;
}

Construction method

The object must be called when it is created, and the constructor has two features:

  • Must have the same name as the class
  • Must have no return type and cannot write void

#Object

Create Object Memory Analysis

public class Pet {
    public String name;
    public int age;

    //Parametric construction
    public void shout(){
        System.out.println("call");
    }
}
public class Application {
    public static void main(String[] args) {
        Pet dog = new Pet();
        dog.name = "Prosperous Money";
        dog.age = 2;
        dog.shout();
        System.out.println(dog.name);
        System.out.println(dog.age);

        Pet cat = new Pet();
        cat.name = "Jocho";
        cat.age = 2;
        cat.shout();
        System.out.println(cat.name);
        System.out.println(cat.age);
    }
}

encapsulation

Programming pursues "high cohesion, coupling". High cohesion means that the internal data details of a class are operated by itself and external interference is not allowed. Low coupling, exposing only a small number of methods for external use

The hiding of data, usually prohibited from directly accessing the actual representation of the data in the object, should be accessed through the operation interface, which becomes the hiding of information

Property private, get/set

public class Student {
    //Property Private
    private String name;
    private int id;
    private char sex;
    private int age;

    //Provide some ways to manipulate this property
    //Provide some get or set methods for public s
    //get gets this number
    public String getName(){
        return this.name;
    }

    //set sets a value for this number
    public void setName(String name){
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getAge() {
        return age;
    }

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

public class Application {
    public static void main(String[] args) {
        Student s1 = new Student();
        //S1.name =';// Private method error
        s1.setName("nwt");
        System.out.println(s1.getName());

        s1.setAge(999);
        System.out.println(s1.getAge());
    }
}
/*
1.Enhance program security and protect data
2.Hide implementation details of code
3.Unified Interface
 */

Rewrite

Override: Need inheritance, subclass overrides parent's method
1. Method names must be the same
2. The parameter list must be the same
3. Modifier: Range can be expanded but not reduced
That is, private can call public, public cannot call private
public>Protected>Default>private
4. Throw an exception: the range can be reduced but not expanded
ClassNotFoundException < Exception

The method of the subclass must be the same as the parent class, but the body of the method is different

Why overrides are required: functional subclasses of a parent class do not necessarily need or satisfy subclasses

public class B {//Overrides are method overrides, not properties
    public void test(){
        System.out.println("B=>test()");
    }
}
public class A extends B{
    @Override//Method override, calling parent class's method by default
    public void test() {
        System.out.println("A=>test()");
    }
    /*Static and non-static methods differ greatly
      Nonstatic methods override parent's methods here
      So the output is A=>test
      Overridden methods are public when needed and cannot be private
     */
}
public class Application {
    public static void main(String[] args) {
        //Method calls are only related to data types defined on the left
        A a = new A();
        a.test();//A

        //References to parent classes point to subclasses
        B b = new A();
        b.test();//B, non-static is A


    }
}

polymorphic

  • Dynamic compilation: enhanced scalability
  • The same method can behave differently depending on who is sending it
  • 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 polymorphisms:

  • There is an inheritance relationship
  • Subclasses Override Methods of Parents
  • Parent Reference Points to Subclass Object

Polymorphism is the method's polymorphism, and attributes have no polymorphism

Polymorphic considerations:
1. Polymorphism is a method polymorphism
2. Parent and child classes are related, otherwise type conversion exception ClassCastException
3. Conditions exist: inheritance relationships, methods need to be overridden, parent references point to subclass objects
father f1 = new Son();

static method cannot be overridden
final constant method cannot be changed
Private private methods cannot be overridden either

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

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

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

public class test {
    public static void main(String[] args) {
        //The actual type of an object is deterministic, but the referential type that can be pointed to is indeterminate
//        new Student();
//        new Person();
        Student s1 = new Student();//The methods that a subclass can call are either its own or inherit from its parent
        Person s2 = new Student();//References to parent classes point to subclasses
        //Parent types can point to subclasses, but cannot call methods unique to subclasses
        Object s3 = new Student();

        s2.run();//Subclass inherits all methods of the parent class
        s1.run();//Subclasses override parent class methods and execute subclass methods

        ((Student)s2).eat();//This method cannot be called without it in the parent class
        //Cast, convert Person to Student type, high to low
        s1.eat();
        //Which methods an object can execute depends primarily on the type on the left side of the object, not much on the right side.
    }
}

instanceof and type conversion

1. References to parent classes point to objects of subclasses
2. Convert subclasses to parent classes for upward transition, no coercion required
3. Conversion from parent to child is a downward transition that requires a cast and may lose some methods
4. Convenient method calls to reduce duplicate code

Abstract: Encapsulation, Inheritance, Polymorphism

Interface: More Abstract

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

public class Student extends Person{
    public void go(){
        System.out.println("go");
    }
}

public class Teacher extends Person{
}


public class test {
    public static void main(String[] args) {
        //The actual type of an object is deterministic, but the referential type that can be pointed to is indeterminate
//        new Student();
//        new Person();
        Student s1 = new Student();//The methods that a subclass can call are either its own or inherit from its parent
        Person s2 = new Student();//References to parent classes point to subclasses
        //Parent types can point to subclasses, but cannot call methods unique to subclasses
        Object s3 = new Student();

        s2.run();//Subclass inherits all methods of the parent class
        s1.run();//Subclasses override parent class methods and execute subclass methods

        ((Student)s2).eat();//This method cannot be called without it in the parent class
        //Cast, convert Person to Student type, high to low
        s1.eat();
        //Which methods an object can execute depends primarily on the type on the left side of the object, not much on the right side.
    }
}

static keyword details

public final class Person {//Person class is modified by final, then it cannot be inherited
    {
        //Anonymous code block, initial value assigned
        System.out.println("Anonymous Code Block");
    }

    static{
        //Static code block, load some initialized data, execute only once
        System.out.println("Static Code Block");//Program exists before loading, so the first output
    }

    public Person(){
        System.out.println("Construction method");
    }

    public static void main(String[] args) {
        Person person1 = new Person();
        System.out.println("===============");
        Person person2 = new Person();
    }
}
public class Student {
    private static int age;//Static variable
    private double score;

    public void run(){
        go();//Non-static calls can be made within static methods
    }

    public static void go(){

    }

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

        new Student().run();
        Student.go();//Static can call static directly
        //Student.run(); // Static cannot call non-static directly

    }
}
import static java.lang.Math.random;//Static Import Package
import static java.lang.Math.PI;

public class test {
    public static void main(String[] args) {
        System.out.println(random());//Write random directly after static package import
        System.out.println(PI);
    }
}

abstract class

  • The Abstract modifier can be used to modify a method or a class. If a method is modified then the method is abstract and the modifier class is abstract.
  • Classes in abstract classes may not have abstract methods, but classes with abstract methods must be declared abstract classes
  • Abstract method: only method declarations have no method implementation; they are used to make subclasses implement
  • If a subclass inherits an abstract class, it must implement an abstract method that the abstract class does not implement, otherwise it must be declared as an abstract class
//Abstract abstract class extends can only inherit singly, interfaces can inherit more
public abstract class Action {
    //Constraint someone to help us achieve
    public abstract void doSmoething();//Method name only without method implementation

}
//All methods of abstract classes that must be implemented by subclasses that inherit them
public class A extends Action{
    @Override
    public void doSmoething() {

    }
}

interface

An interface is a specification, defines a set of rules, and cannot write its own methods

Professional constraints, separation of constraints and Implementation

The function of the interface:
1. Constraints
2. Define some methods for different people to implement
3. Method defaults to public abstrac
4. Constants default to public static final
5. Interfaces cannot be instantiated and there is no construction method in the interface
6.implements implement interfaces that implement multiple interfaces but must override their methods

//Interfaces are defined with interface ts, which require implementation classes
public interface UserService {
    //All defined methods in an interface are abstract public

    //Constant defaults to public static final
    int AGE = 99;

    void run(String name);
    void delete(String name);
    void update(String name);
    void query(String name);


}
//Classes can implement interfaces through implements, but methods must be overridden
public class UserServiceImpl implements UserService,TimeService{//Implement multiple interfaces, side-by-side multiple inheritance

    @Override
    public void run(String name) {

    }

    @Override
    public void delete(String name) {

    }

    @Override
    public void update(String name) {

    }

    @Override
    public void query(String name) {

    }

    @Override
    public void timer() {

    }
}

N Internal Classes

An internal class is to define another class inside a class, for example, a class B in class A, B is an internal class relative to A, A is an external class relative to B

  • Member Inner Class
  • Static Internal Class
  • Local Internal Class
  • Anonymous Inner 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 a method of an internal class");
//        }
//
//        //Internal class accesses external class
//        public void getID(){
//            System.out.println(id);
//        }
//    }

    public void method(){
        class Inner{
            //Local Internal Class
            public void in(){

            }
        }
    }
}

class A{
    //There can be more than one class in a java class, but only one public class

}
public class test {
    public static void main(String[] args) {
//        Outer outer = new Outer();
//
//        //Instantiate internal classes through external classes
//        Outer.Inner inner = outer.new Inner();
//        inner.getID();


        //Apple apple = new Apple();
        new Apple().eat();//No name to initialize class, no instance to save to object

        UserService userService = new UserService(){

            @Override
            public void hello() {

            }
        };

    }
}

Error and Exception

Five keywords for exception handling:

  • try,catch,finally,throw,throws

[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-gMxBY4zg-1658142437120).) https://img.jbzj.com/file_images/article/202112/20211224170011560.jpg )]

Custom Exception

Using java's built-in exception classes can describe most of the exceptions that occur during programming. In addition, users can customize exceptions by simply inheriting the Exception class

Use custom exception classes:

1. Create a custom exception class

2. Throw an exception object in the method with the throw keyword

3. If you handle exceptions in the current method that throws exceptions, you can use the try-catch statement to capture and handle them; Otherwise, at the declaration of the method, the exception known to the method caller by the throws keyword proceeds to the next step

4. Catch and handle exceptions in callers of exception methods

Tags: Java programming language

Posted by timetomove on Tue, 19 Jul 2022 01:24:52 +0530