Java object oriented programming

Posted by samirk on Wed, 12 Jan 2022 20:42:05 +0100

What is object oriented?

  1. Object oriented programming (OOP)
  2. The essence of object-oriented programming is to organize code by class and data by object.
  3. Three characteristics:
    1. Encapsulation: encapsulate the data and open a small port for extraction.
    2. Inheritance: a subclass inherits everything from its parent class.
    3. Polymorphism: a method has many forms and behaves differently.

Definition of method

  1. Modifier
  2. Return type
  3. break: jump out of the swich, end the loop and return
  4. Method name: pay attention to the naming standard and see the meaning of the name.
  5. Parameter list: (parameter type, parameter name)
  6. Exception thrown: question
//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 ends the method and returns a result!
    public String sayHello(){
        return "Hello,world";
    }
    public int max(int a,int b){
        return a>b ? a : b;//Ternary operator 
    }
    //Exception throw
    public  void readFile(String fille) throws IOException{
    }
}

Method call: recursion

  1. Static method
  2. Non static method
  3. Actual parameter and formal parameter: the types of actual parameter and formal parameter should correspond.
  4. Value passing and reference passing
  5. this keyword
    public static void main(String[] args) {
        //Instantiate this class new
        //Object type object name = object value;
        Student student = new Student();
        student.say();
    }
    //static is loaded with the class
    public void a(){
        b();
    }
    //Class does not exist until it is instantiated
    public void b(){
    }
---------------------------------------------------------
    //Student class
public class Student {

    //method
    public void say(){
        System.out.println("The students are talking!");
    }
}

---------------------------------------------------------  
    //Arguments and formal parameters
    public static void main(String[] args) {
        //The first method: new demo03() add();
        //The second static method: add static
        //The types of actual parameters 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 passing: essence or value passing
    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 is an object: the pointed -- > perosn perosn = new perosn(); This is a specific person who can change attributes.
        perosn.name = "A";
    }
}
//Defines a Perosn class with an attribute: name
class Perosn{
    String name;
}

Object like relationships

When using the new keyword, in addition to allocating memory space, the created object will be initialized by default and the constructor in the base will be called.

Class is an abstract template. Different instances can be created through the new keyword.

There are two cores in the constructor:

  1. To use the new keyword, you must have a constructor
  2. Used to initialize values
//Student class
public class Student {
    //Properties: Fields
    String name;
    int age;

    //method
    public void study(){
        System.out.println(this.name+"Students are studying");
    }
}
//--------------------Boundary ()----------------------
//There should be only one main method in a project
public class Application {
    //Class is abstract and needs to be instantiated
    //Class instantiation will return an object of its own!
    //xiaoming object is a concrete instantiation of Student class
    public static void main(String[] args) {
        Student xiaoming = new Student();
        Student xh = new Student();
        xiaoming.name = "Xiao Ming";
        xh.name = "Xiao Hong";
        xiaoming.age = 3;
        xh.age = 3;
        System.out.println(xiaoming.name);
        System.out.println(xiaoming.age);
        System.out.println(xh.name);
        System.out.println(xh.age);
    }
}

Parameterized Construction: once a parameterized construction is defined, the definition must be displayed if there is no parameter

//java --> class
public class Person {
    /*
    Even if a class doesn't write anything, it will have a method
    Display definition constructor
     */
    String name;
    //Instantiation initial value
    public Person(){}
    //Parameterized Construction: once a parameterized construction is defined, the definition must be displayed if there is no parameter
    public Person(String name){
        this.name = name;
    }
}
//----------------Demarcation----------------
public class Application {
    public static void main(String[] args) {
        //new instantiates an object
        //Person person = new Person();
        
        Person name = new Person("zhangj");
        System.out.println(name.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:
    1. After defining a parameterized construct, if you want to use a lunch construct, the displayed definition is a parameterized construct
 Shortcut keys:
    1. Alt + Insert
this.xxx = xxx;

Create object memory analysis

1.Application have
    main method
    Constant pool = Wangcai
2.Pet have
    name
    age
    shout()
    go back to Application new One Pet
3.dog have
    name = null from Application Li constant pool: Wangcai extracted to name
    age = 0
    shout()
    return Pet name = "Wangcai"; age = 1;
    output dog.name = Wangcai ; age = 1;
public class Application {
    public static void main(String[] args) {
        Pet dog = new Pet();
        dog.name = "Wangcai";
        dog.age = 1;
        dog.shout();
        System.out.println(dog.name);
        System.out.println(dog.age);

        //Pet cat = new Pet();
    }
}
//-----------------Demarcation-----------------
public class Pet {
    public String name;
    public int age;

    //Nonparametric structure
    public void shout(){
        System.out.println("Let out a cry");
    }
}

encapsulation

What should be leaked, what should be hidden

  1. Our program design should pursue "high cohesion, low coupling". High cohesion: 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.
  2. Property private, get/sat

Meaning of encapsulation

  1. Improve program security and protect data.
  2. Implementation details of hidden code.
  3. Unified interface
  4. System maintainability
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 attributes!
    // Some public get sat methods are provided

    //get gets this data
    public int getAge(){
        return this.age;
    }
    //set sets a value for this data
    public void setAge(int age){
        if (age>120 || age<0){
            this.age = 3;
        }else {
            this.age = age;
        }
    }
}
//-----------------Demarcation------------------
public class Application {
    public static void main(String[] args) {
        Student s1 = new Student();

        s1.setAge(999);

        System.out.println(s1.getAge());
    }
}

inherit

Extensions means extension, and subclasses are extensions of parent classes.
java has only single inheritance, not multiple inheritance. "A son can be followed by a father", and a father can have multiple sons.

A subclass inherits from the parent class and will have all the methods of the parent class.

super

  • super note:
    1. super calls the constructor of the parent, which must be in the first of the constructor.
    2. super must only appear in subclass methods or constructors!
    3. super and this cannot call constructor at the same time!
  • VS this:
    • The objects represented are different:
      1. This: used to represent the current object of this class.
      2. super: represents a reference to a parent object.
    • premise
      1. this: can be used without inheritance
      2. super: can only be used under inheritance conditions
    • Differences in construction methods
      1. this(); Call the constructor of this class
      2. super(); Call the construction of the parent class
package com.oop.demo05;
//Person -- > parent class
public class Person {
    public Person() {
        System.out.println("Person Nonparametric execution");
    }
//-------------------------------------------
    protected String name = "zhang";
//-------------------------------------------
    //Private -- > private things cannot be inherited
    public void print(){
        System.out.println("Person");
    }
}
//----------------Demarcation------------------
package com.oop.demo05;
//Student: derived class -- > subclass
public class Student extends Person {
//-------------------------------------------------
    public Student() {
        //Hidden code: the parameterless construction of the parent class is called by default
        //super();// Calling the constructor of the parent class must be on the first line of the subclass
        System.out.println("Student Nonparametric execution");
    }

    public Student(String nama) {
        this.nama = nama;
    }
//-----------------------------------------------------
    private String nama = "jinghua";
//-----------------------------------------------------
    public void print(){
        System.out.println("Student");
    }
    public void test1(){
        print();//Student
        this.print();//Student
        super.print();//Person
    }
//------------------------------------------------------
    public void test(String name){
    }
}
//-------------------Demarcation-------------------------------
package com.oop;

import com.oop.demo05.Student;
import com.oop.demo05.Person;

public class Application {

    public static void main(String[] args) {

        Student student = new Student();
        //student.test("Zhang");
        //student.test1();

    }
}

Method rewrite

Overrides are written by methods, and overrides have nothing to do with properties.

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
  • Overrides must be public and cannot be private
  • Override: override
  • Override: 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 range can be expanded but not reduced; Public>Protected>Default>private
    4. Exception thrown: the range can be narrowed, but not enlarged; ClassNotFoundException – > exception (large)

Override: the methods of the child class and the parent class must be consistent; Method body is different!

  • Why rewrite;
    1. The function subclass of the parent class may not be required or satisfied!

 

public class B {
    public void test(){
        System.out.println("B==>test");
    }
}
//------------------Demarcation---------------------
public class A extends B{
    //Override: override
    @Override//Annotation: annotation with function
    public void test() {
        System.out.println("A==>test");
    }
}
//----------------Demarcation------------------------
public class Application {
    //Static methods are very different from non static methods
    public static void main(String[] args) {
        //Method is only related to the data type defined on the left
        A a = new A();
        a.test();//A
        //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();//B
    }
}

polymorphic

The actual type of an object is determined, and the reference type that can be pointed to is uncertain. "The reference of the parent class can only think of the child class"

The methods executed by the object mainly depend on the type on the left of the object, which has little to do with the type on the right.

The methods that students can call are their own or inherit the parent class.

The Person parent type can point to subclasses, but cannot call methods unique to subclasses.

  • Polymorphic considerations
    1. Polymorphism is the polymorphism of methods, and there is no polymorphism of attributes.
    2. The parent class is related to the child class. Can't the cat? Into a dog? Otherwise, a type conversion exception will occur: ClassCastException
    3. Polymorphic existence conditions: inheritance relationship - the method needs to override "which type is executed, and both have execution subclasses" - the parent class reference points to the subclass
      1. static method: belongs to class, not instance
      2. final constant: cannot be overridden
      3. Private method: private cannot be overridden
public class Person {
    public void run(){
        System.out.println("run");
    }
}
//----------------Demarcation---------------
public class Student extends Person{
    @Override
    public void run() {
        System.out.println("son");
    }

    public void eat(){
        System.out.println("eat");
    }
}
//---------------Demarcation-------------
public class Application {
    public static void main(String[] args) {
        Student s1 = new Student();
        Person s2 = new Student();
        Object s3 = new Student();

        s2.run();
        s1.run();
    }
}

instanceof

  1. A parent class reference points to a child class object
  2. The subclass is converted to the parent class and transformed upward: no forced conversion is required
  3. If the parent class is converted to a child class, some methods will be lost in the downward Transformation: cast“
  4. Convenient method call and reduce duplicate code! Make code concise
  5. System.out.println(X instanceof Y);// Can it be compiled
    //Object > String
    //Object > Person > Teacher
    //Object > Person > Student
    public static void main(String[] args) {
        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);//flase
        System.out.println(Object instanceof String);//flase
    }

Student converts this object to student type, and we can use the method of student type

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

static keyword explanation

There is only one static variable in the class, which can be shared by instances in the class.

static is born with the class and is executed only once.

static is a subordinate class. Other people can't use it. Only this class can use it.

Abstract: abstract class

  1. abstract modifier, which can be used to modify methods or classes
    1. If you modify a method, it is an abstract method
    2. If you modify a class, it is an abstract class
  1. All methods of an abstract class can only be implemented by subclasses: constraints!
  2. Ordinary methods can be written in abstract classes
  3. Abstract methods must be in abstract classes

abstract cannot be combined with static , virtual, final and native

  1. You can't use the abstract class new. You can only implement it by subclasses: constraints!
  2. Ordinary methods can be written in abstract classes
  3. Abstract methods must be written in abstract classes
public abstract class Action {

    public abstract void doSomething();

}
//--------------------Demarcation------------
//All methods of an abstract class that inherit its subclasses must implement its methods~
//Unless the subclass is also abstract, let the subclass implement
public class A extends Action{
    @Override
    public void doSomething() {

    }
}

Interface

The interface has only specifications and cannot write its own methods~

All definitions in the interface are actually abstract

All interfaces are public abstract by default

 

public interface UserService {
    void run();
    void delete();
    void update();
    void query();
}
//--------------------Demarcation-------------
public interface TimeService {
    void Timer();
}
//---------------Demarcation----------------
//Abstract class: extends (only single inheritance, not multiple inheritance)
//Class can implement the interface through: implements
//If you implement the class of the interface, you need to rewrite the methods in the interface!
public class UserServiceImpl implements UserService,TimeService{
    @Override
    public void run() {

    }

    @Override
    public void delete() {

    }

    @Override
    public void update() {

    }

    @Override
    public void query() {

    }

    @Override
    public void Timer() {

    }
}
  • effect:
    1. Role of constraints
    2. Some methods are defined for different people to implement.
    3. All methods are public abstrace
    4. Constants are public sterst final
    5. The interface cannot be instantiated ~ because there is no constructor in the interface.
    6. implements can implement multiple interfaces
    7. To create an interface, you must override the methods in the interface

Inner class

Inner class is to define another class inside a class.

A java class can have multiple class classes, but only one public class

Member inner class

The inner class can get the private properties of the outer class

public class Outer {

    private int id = 10;
    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.");
        }

        //The inner class can get the private properties of the outer class
        public void getID(){
            System.out.println(id);
        }
    }
}
//-------------------Demarcation--------------
public class Application {
    public static void main(String[] args) {
        //new Outer first
        Outer outer = new Outer();
        //Instantiate the inner class through this outer class
        Outer.Inner inner = outer.new Inner();
        inner.getID();
    }
}

Static inner class

public class Outer {

    private int id = 10;
    public static void out(){
        System.out.println("This is the method of an external class.");
    }

    public static class Inner {
        public void in(){
            System.out.println("This is the method of the inner class.");
        }

        //The inner class can get the private properties of the outer class
        public void getID(){
            System.out.println(id);
        }
    }
}
//----------------------Demarcation-----------------
public class Application {
    public static void main(String[] args) {
        //new Outer first
        Outer outer = new Outer();
        //Instantiate the inner class through this outer class
        Outer.Inner inner = outer.new Inner();
        inner.getID();
    }
}

Anonymous Inner Class

public class Test {
    public static void main(String[] args) {
        //There is no name to initialize the class, so there is no need to save the instance in the variable
        new Apple().eat();

        new UserService(){
            @Override
            public void hello() {

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

Exception: exception

Exceptions are run-time. What is generated during compilation is not an Exception, but an Error.

At the beginning, everyone identified the Error caused by program design as not an Exception.

However, Error is generally regarded as an exception, so exceptions are generally divided into two categories: Error and exception.

  • There are three types of exceptions:
    1. Checking exceptions: the most representative exceptions are those caused by user errors or problems.
    2. Runtime exception: an exception that may be avoided by the programmer.
    3. ERROR: an ERROR is not an exception, but a problem out of the programmer's control. Column such as stack overflow
  • Java treats exceptions as objects and defines a base class java Lang. throwable is the superclass of all exceptions.

 

These exceptions are generally caused by program logic errors. The program should avoid such exceptions as far as possible from low logic;

The difference between Error and Exception: Error is usually a catastrophic Error, Exception can be handled by the program under normal circumstances, and these exceptions can be handled in the area of the program as much as possible.

Catch / throw exception

Exception Keywords: try, catch, finally, throw, throws

try {monitor exceptions} catch() {"exceptions you want to catch" catch exceptions} finally {deal with aftermath work "finally area can not"}

Throw: actively throw an exception, which is generally used in methods.

throws: if you can't handle this exception in the method, throw an exception on the method.

Assumption: catch multiple exceptions from small to large

Shortcut keys: Ctrl+Alt+T, auto generate

public class Text1 {
    public static void main(String[] args) {

        int a =1;
        int b =0;

        try { //Monitoring area
            System.out.println(a/b);
        }catch(ArithmeticException){ //Catch exception
            System.out.println("Program exception!");
        }finally{ //Deal with the aftermath
            System.out.println("finally");
        }
        
    }
}
//-----------------------Demarcation------------------
public class Text1 {
    public static void main(String[] args) {

        int a =1;
        int b =0;

        try { //Monitoring area
            System.out.println(a/b);
        }catch(Error c){ //Catch (exception you want to catch)
            System.out.println("Program exception!");
        } catch(Exception r){
            System.out.println("Exception");
        }catch (Throwable y){
            System.out.println("Throwable");
        }finally{ //Deal with the aftermath
            System.out.println("finally");
        }

    }
    public void q(){f();}
    public void f(){q();}
}
//-----------------------Demarcation-----------------
public class Test3 {
    public static void main(String[] args) {
        try {
            new Test3().test(1,0);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
    }
    //If this exception cannot be handled in the method, it is thrown on the method.
    public void test(int a,int b)throws ArithmeticException{
        if (b==0){
            throw new ArithmeticException();//Actively throw exceptions, which are generally used in methods
        }
    }
}

Custom exception

//Custom exception
public class MyExcepion extends Exception{
    //Transfer number > 10;
    private int detail;

    public MyExcepion(int a) {
        this.detail = a;
    }
    //toString abnormal print information.
    @Override
    public String toString() {
        return "MyExcepion{" +
                "detail=" + detail +
                '}';
    }
}
public class Test {

    //There may be abnormal methods
    static void test(int a)throws MyExcepion{
        System.out.println("The parameters passed are:"+a);
        if (a>10){
            throw new MyExcepion(a);
        }
        System.out.println("OK");
    }
    public static void main(String[] args) {
        try {
            test(11);
        } catch (MyExcepion e) {
            System.out.println("MyExcepion=>"+e);
        }
    }
}

Topics: Java Back-end