Java basic syntax

Object oriented definition

What is object-oriented

Object oriented nature:

Method definition and call

Creation of classes and objects


Example code:

package com.gavin.oop;

public class Student {

    //Attribute value
    String name;
    int age;

    //method
    public void study() {
        System.out.println(this.name + "I'm learning");
    }
}

package com.gavin.oop;

public class Application {

    public static void main(String[] args) {

        //Instantiate student class
        Student xiaoming = new Student();
        Student xiaohong = new Student();

        //Assign a value to the instantiated xiaoming object
        xiaoming.name = "Zhang San";
        xiaoming.age = 23;
        System.out.println(xiaoming.name);
        System.out.println(xiaoming.age);

        System.out.println(xiaohong.name);
        System.out.println(xiaohong.age);
    }
}

Execution results:

Object oriented nature:

Constructor details


Example code:

package com.gavin.oop;

public class Person {

    String name;

    int age;

    //Parameterless constructor
    //The new keyword is used to create an object, which essentially calls the constructor
    //The constructor is used to initialize the value
    public Person() {
    }

    //Parametric constructor
    //Once a parameterized constructor is defined, a nonparametric constructor should also be defined
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

package com.gavin.oop;

public class Application2 {

    public static void main(String[] args) {
        //Assign a value to an attribute in a Person object using a parameterized constructor
        Person person = new Person("Zhang San", 23);
        System.out.println(person.name);
        System.out.println(person.age);
    }
}

Execution results:

Create object memory analysis

Packaging details


Example code:

package com.gavin.oop;

public class Person2 {

    //The attribute value is decorated with private, indicating private
    private String name;

    private int age;

    //The set method is used to set the value of the property
    public void setName(String name) {
        this.name = name;
    }

    //The get method is used to get the value of the property
    public String getName() {
        return name;
    }

    //The set method can be defined by itself to verify whether the incoming value is legal
  public void setAge(int age) {
        if (age > 120 || age < 0) {
            this.age = 3;   //wrongful
        } else {
            this.age = age; //legitimate
        }
    }

    public int getAge() {
        return age;
    }
}

package com.gavin.oop;

public class Application3 {

    public static void main(String[] args) {
        Person2 person2 = new Person2();
        person2.setName("Zhang San");
        //Illegal value passed in
        person2.setAge(123);
        System.out.println(person2.getName());
        System.out.println(person2.getAge());
    }
}

Execution results:

Function of encapsulation:

  1. Improve program security and protect data
  2. Implementation details of hidden code
  3. Unified interface
  4. The maintainability of the system has increased

inherit


Example code:
First define a Person class with money attribute and say() method

package com.gavin.oop.Demo05;

public class Person {

    private int money;

    public int getMoney() {
        return money;
    }

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

    public void say() {
        System.out.println("Humans can talk");
    }
}

Define a Student class, and use the extends keyword to inherit the Person class

package com.gavin.oop.Demo05;

public class Student extends Person{

    public static void main(String[] args) {
        Student student = new Student();
        student.setMoney(100000000);
        System.out.println("money=" + student.getMoney());
        student.say();
    }
}

Execution results:

After the Student class inherits the Perosn class, it has the money attribute and the say method in the Person class, which is the meaning of inheritance. Inheritance in Java is single inheritance, that is, after the Student class inherits the Person class, it can no longer inherit other classes, and the Person class can also be inherited by other classes. This is equivalent to the fact that in real life, a son has only one father, and a father can have multiple sons.

super detailed explanation

Super keyword is used in Java inheritance. Subclasses can use super to call properties and methods in classes
Example code:
First, define a Person class with the name attribute, assign it to Zhang San, and a print method

package com.gavin.oop.Demo05;

public class Person {

    protected String name = "Zhang San";

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

Then define a Student class, which also has the name attribute and the print method, and assign the name attribute Li Si

package com.gavin.oop.Demo05;

public class Student extends Person{

    private String name = "Li Si";

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

    public void test(String name) {
        System.out.println(name);
        System.out.println(this.name);
        System.out.println(super.name);
        System.out.println("Call method");
        this.print();
        super.print();
    }
}

The calling method in the test class and the parameter passed to the name parameter is Wang Wu.

package com.gavin.oop.Demo05;

public class Application {

    public static void main(String[] args) {
        Student student = new Student();
        student.test("Wang Wu");
    }
}

Execution results:

It can be seen that using the super keyword in the subclass, you can call the properties and methods in the parent class
Precautions for using the super keyword:

Method rewrite

After a subclass inherits from the parent class, it can override the methods in the parent class to meet its own needs
Example code:
First create a class B object with a test() method

package com.gavin.oop.Demo05;

public class B {

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

Create A class A object to inherit class B, and then override the test() method in class B

package com.gavin.oop.Demo05;

public class A extends B{

    @Override
    public void test() {
        System.out.println("A==>test()");
    }
}

Test class code:

package com.gavin.oop.Demo05;

public class Application {

    public static void main(String[] args) {
        A a = new A();
        a.test();
        //A parent class reference points to a child class object
        B b = new A();
        b.test();
    }
}

Execution results:

It can be seen that the execution results of the test() method of class B and A are the same. The reason is that class A rewrites the test() method in class B, so that the test() method in class B is the same as the test() method in subclass

What is polymorphism


Example code:
First create a Person object with a run() method

package com.gavin.oop.Demo06;

public class Person {

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

Create a Student object to inherit the Person class, override the run() method, and add an eat method

package com.gavin.oop.Demo06;

public class Student extends Person{

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

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

Test class code:

package com.gavin.oop.Demo06;

public class Application {

    public static void main(String[] args) {
        /**
         * The actual type of an object is determined, the reference type that can be pointed to is uncertain, and the reference of the parent class points to the child class object
         */
        //The methods that students can call are their own or inherit the parent class
        Student student = new Student();
        //The Person type can point to subclasses, but cannot call methods in subclasses
        Person person = new Student();

        student.run();
        person.run();

        //The methods that can be executed by an object mainly depend on the type on the left of the object, which has little to do with the type on the right
        student.eat();
        //person.eat();  Methods in subclasses cannot be called in a parent class

    }
}

Execution results:

Precautions:

instanceof keyword

instanceof keyword is mainly used to judge whether two objects or values are of the same type. If the same type returns true, it means that they can be forcibly converted. If they are not of the same type, it returns false and cannot be forcibly converted.

Example code:

package com.gavin.oop.Demo06;

public class Person {

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

package com.gavin.oop.Demo06;

public class Student extends Person{

}

package com.gavin.oop.Demo06;

public class Teacher extends Person{
}

package com.gavin.oop.Demo06;

public class Application {

    public static void main(String[] args) {
        /**
         * Object -> Person -> Student
         * Object -> Person -> Teacher
         * Object -> String
         */
        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);  //true
        System.out.println(object instanceof String);   //true
        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);      An error is reported when compiling. It cannot be compiled
    }
}

It can be seen that if there is a parent-child inheritance relationship, it returns true, indicating that coercion can be performed.

static keyword explanation

Static keyword can be used to modify variables, constants and methods in a class. After static modification, you can directly use the object name instead of creating an object To call variables, constants, and methods.
Example code:

package com.gavin.oop.Demo07;

public class Student {

    //Static variable
    private static int age;

    //Non static variable
    private double score;

    public static void main(String[] args) {
        Student student = new Student();
        //Using static, you can call directly using the class name
        System.out.println(Student.age);
        System.out.println(student.age);
        System.out.println(student.score);
    }
}

Execution results:

Anonymous code block, static code block, execution order of construction method
Example code:

package com.gavin.oop.Demo07;

public class Person {

    {
        System.out.println("Anonymous code block");
    }

    static {
        System.out.println("Static code block");
    }

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

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

Execution results:

It can be seen that the static code block is executed first, then the anonymous code block, and finally the construction method, and the static code block is executed only once with the class loading.

Static import package example code:

package com.gavin.oop.Demo07;

//Static import package
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);
    }
}

Execution results:

After statically importing the package, you can call the method by directly writing the method name when using the method.

abstract class


Example code:

package com.gavin.oop.Demo08;

//Use abstract to represent abstract classes
public abstract class Action {

    //Abstract modification is used to represent abstract methods
    public abstract void doSoming();

    //You can also write dandelion methods in abstract classes
    public void say() {
        System.out.println("speak");
    }
}

package com.gavin.oop.Demo08;

public class A extends Action{
    
    //Inherits methods that are not implemented in the abstract class to be overridden
    @Override
    public void doSoming() {
        System.out.println("work ing");
    }
}

package com.gavin.oop.Demo08;

public class Application {

    public static void main(String[] args) {
        //new Action() abstract class cannot be instantiated
        //It can only be instantiated if it inherits the subclass of the abstract class
        A a = new A();
        a.doSoming();
    }
}

Execution results:

Notes on abstract classes:

Definition and implementation of interface


Example code:

package com.gavin.oop.Demo09;

//Interface defines the keyword of the interface. All interfaces need to be implemented by the class
public interface UserService {

    //Define methods in interfaces
    //All definitions in the interface are abstract public static
    void add(String name);
    void update(String name);
    void delete(String name);
    void query(String name);
}

package com.gavin.oop.Demo09;

public interface TimeService {

    void timer();
}

package com.gavin.oop.Demo09;

//Class uses the implements keyword to implement the interface
//If the class implements the interface, it is necessary to override the methods in the interface
//Multiple inheritance can be implemented using interfaces
public class UserUserviceImpl implements UserService, TimeService{
    @Override
    public void timer() {

    }

    @Override
    public void add(String name) {

    }

    @Override
    public void update(String name) {

    }

    @Override
    public void delete(String name) {

    }

    @Override
    public void query(String name) {

    }
}

Function of interface:

Inner class


Member inner class example code:

package com.gavin.oop.Demo10;

public class Outer {

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

    class Inner{
        public void in() {
            System.out.println("This is the method of the inner class");
        }
        //Gets the private property of the external class
        public void getAge() {
            System.out.println(age);
        }
    }
}

package com.gavin.oop.Demo10;

public class Application {

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

Execution results:

The above is the specific usage of member inner classes. Other inner classes can try to write them themselves.

Keywords: Java

Added by xwhitchx on Thu, 06 Jan 2022 17:28:32 +0200