Review the object-oriented of java basic syntax

Posted by PhaZZed on Sun, 23 Jan 2022 21:45:57 +0100

This article will review the object-oriented features in java

Basic concepts

Object oriented organizes code in the form of classes and encapsulates data in the form of objects
Three characteristics of object-oriented encapsulation inheritance polymorphism
There are objects first and then classes. Objects are concrete things and concrete instances of abstract concepts. Classes are abstract and abstract objects

object

Creating an object with static keyword is a static method that belongs to a class rather than an object
Methods without static keyword only exist after class instantiation

public class Student {
    //Loaded with class
    public static void sayHello(){
        System.out.println("Hello");
    }
    //Class does not exist until it is instantiated
    public void sayHi(){
        System.out.println("hi");
    }
}

Call these two methods separately

 		//Call static method class name Method name
        Student.sayHello();
        //Call member method
        Student student = new Student();
        student.sayHi();

For value passing and reference passing in java, see the following two methods

	public static void change(Person p){
        p.name = "abc";
    }
    public static void change(String s){
        s = "abc";
    }

The first way to call these two methods is value passing, which will not change the content of s
The second type of reference passing is that the reference (pointer) of the object will change the content

		String s = "aaa";
        change(s);
        System.out.println(s); //aaa

        Person p1 = new Person();
        change(p1);  //Reference passing
        System.out.println(p1.name); //abc

Construction method

When the constructor (constructor) creates an object, it will call
If you do not write, there will also be a constructor (default parameterless constructor)
If you write a parameterless constructor, you don't have a parameterless constructor, but you usually write a parameterless constructor
The constructor name must be the same as the class name and have no return value
Its purpose is to instantiate some objects
alt+insert in idea can automatically generate constructors
This keyword refers to this class. Whoever calls this class is who
The program should pursue high cohesion and low coupling

public class Student {
    String name;
    int age;
    
    public Student(){
    }
    
    public Student(String name , int age){
        this.name = name;
        this.age = age;
    }
    
    public void study(){
        System.out.println(this.name + " is study");
    }
}

Test in main method

        Student student = new Student();
        student.name = "Jack";
        student.study();

        Student student2 = new Student("Bob", 24);
        System.out.println(student2.name + " " + student2.age);

encapsulation

Generally speaking, it is to encapsulate the data and provide an interface to the outside world
Improve the security of the program, hide the details of the code, unify the interface, and improve the maintainability of the system
Simply put, private properties provide set get
See the code private keyword below so that attributes and methods can only be accessed in other classes in this class.

class Student{
    //Property private get set
    private String name;
    private int age;

    //Provide public get set method
    public String getName(){
        return this.name;
    }

    public void setName(String name){
        this.name = name;
    }
}

Call setter and getter methods

	 public static void main(String[] args) {
        Student student = new Student();
        student.setName("Jerry");
        System.out.println(student.getName());
    }

inherit

The essence of inheritance is the abstract implementation of classes and better modeling of the real world
If a subclass inherits from the parent class, it will have all the non private methods and properties of the parent class
Properties and methods that use the private keyword are not inherited
Classes decorated with final cannot be inherited
Scope of application public protected default private
In java, all classes inherit the object class
java can only inherit a single subclass, and can only have a parent class

Please see the following code. There is no say() method in the subclass, but the method of the parent class can be called after inheriting (extends keyword)

public class Test01 {
    public static void main(String[] args) {
        Student student = new Student();
        student.say(); //hello
    }
}

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

class Student extends Person{
    //A subclass is an extension of the parent class
}

Use the super keyword to access the properties and methods of the parent class

public class Test01 {
    public static void main(String[] args) {
        Student student = new Student();
        student.test(); // Teemo Teemo jack
        student.test2(); //test hello
    }
}


class Person{
    protected String name = "jack";

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

class Student extends Person{
    //A subclass is an extension of the parent class
    private String name = "Teemo";

    public void test(){
        System.out.println(name);
        System.out.println(this.name);
        System.out.println(super.name);
    }
    
    public void say(){
        System.out.println("test");
    }

    public void test2(){
        say();
        super.say();
    }
}

When a subclass creates an object after inheriting the parent class, it will call the parameterless constructor of the parent class by default
The reason is that a super() is hidden in the parameterless construction of the subclass; This method calls the parameterless construct of the parent class
This sentence can only be placed on the first line or super(xxx); Put the parameters inside (the parameterized constructor of the parent class)
Of course, you can use this(); Instead of (calling the parameterless construction of subclasses), of course, it can only be placed on the first line of the constructor

	public Student(){
        super("jack");
    }

As for method rewriting, when a method is written out in a subclass, and the return value of the method name is consistent with the parameter type (the range of modifiers can be expanded, and the thrown exceptions can be reduced but not expanded) (the final modification cannot be overridden), calling this method in a subclass will give priority to calling the written method of the subclass. Please see the following code

public class Test01 {
    public static void main(String[] args) {
        B b = new B();//Method rewrite
        b.test1(); //B test1
    }
}

class A{
    public void test1(){
        System.out.println("A  test1");
    }
}

class B extends A{
    public void test1(){
        System.out.println("B test1");
    }
}

polymorphic

Polymorphism can enable us to compile dynamically, make the program more extensible, and make the program more flexible
Polymorphism is the polymorphism attribute of a method. There is no polymorphism
Parent and child classes must have a relationship
I understand that when s2 calls a method, if the method cannot be found in the parent class, it cannot be called (for example, test2() method). After finding it, check whether the subclass has been rewritten. If so, call the rewritten method
s1 is directly found in the subclass. If the method cannot be found in the parent class, it is also called after rewriting

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

        Student s1 = new Student();
        //A reference to a parent class points to a child class
        Person s2 = new Student();
        Object s3 = new Student();

        //When a subclass overrides the method of the parent class, it calls the method of the subclass
        s2.test1(); //Student test2
        //Call the method of the parent class without overriding
        s2.test3(); //Person test3
    }
}

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

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

Look at the following code. The parent type reference points to the child type object, looking for the left class

public class Test01 {
    public static void main(String[] args) {
        A a = new B();
        B b = new B();//Method rewrite
        a.test1(); //B test1
        b.test1(); //B test1

        //The static method belongs to a class
        a.test2(); //static A
        b.test2(); //static B

    }
}

class A{
    public void test1(){
        System.out.println("A  test1");
    }

    public static void test2(){
        System.out.println("static A");
    }
}

class B extends A{
    public void test1(){
        System.out.println("B test1");
    }

    public static void test2(){
        System.out.println("static B");
    }
}

About instanceof keyword
Whether the object can be compiled or not is whether the class where the object is created has an inheritance relationship with the class behind instanceof
true and false are determined by whether the concrete instance on the right side of the object and the instance of can be transformed into each other

public class Test01 {
    public static void main(String[] args) {
        //Whether the object can be compiled or not is whether the class where the object is created has an inheritance relationship with the class behind instanceof
        //true and false are determined by whether the concrete instance on the right side of the object and the instance of can be transformed into each other
        Person s1 = new Student();
        System.out.println(s1 instanceof Student); //true
        System.out.println(s1 instanceof Person); //true
        System.out.println(s1 instanceof Teacher); //false
        Student s2 = new Student();
        System.out.println(s2 instanceof Student); //true
        System.out.println(s2 instanceof Person); //true
        
        ((Student)s1).go();  //Forced type conversion
    }
}

class Person{

}

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

class Teacher extends Person{

}

static keyword remember that it exists in the method area and belongs to the class. See the following code

public class Test02 {
    static int i = 0;
    {
        //Code block (anonymous code block)
        System.out.println("Anonymous code block");
    }
    static {
        //Static code block
        //Class is executed only once when it is loaded
        System.out.println("Static code block");
    }
    public Test02(){
        System.out.println("constructor ");
    }
    public static void main(String[] args) {
        Test02 t = new Test02();
        /*
          Static code block
          Anonymous code block
          constructor 
          */
        test();
        test();
        System.out.println(i);  //2
    }
    public static void test(){
        i++;
    }
}

abstract class

Abstract classes are decorated with abstract
Abstract methods have only the name of the method and no implementation of the method
Abstract classes can have ordinary methods
Abstract methods in class must be abstract classes
An inherited abstract class must implement all of its abstract methods unless it is abstract

public abstract class Action {
    public abstract void doSome();
}

class A extends Action{
    @Override
    public void doSome() {
        System.out.println("doSome");
    }
}

Interface

An interface is a specification that defines a set of rules
The methods in the interface are abstract public abstract
Classes can implement multiple inheritance (pseudo multiple inheritance) using interfaces
The implementation class must implement all methods defined by the interface
Look at the code

public interface UserService {
    void add(String name);
    int query(int num);
}
public class UserServiceImpl implements UserService {

    @Override
    public void add(String name) {
        System.out.println("add");
    }
    @Override
    public int query(int num) {
        System.out.println("query");
        return -1;
    }
}

Inner class

public class Outer {
    private int id;
    public void out(){
        System.out.println("out");
    }
    class Inner{
        //You can get private properties and private methods of external classes
        public void in(){
            id = 10;
            System.out.println(id);
            System.out.println("in");
        }
    }
}
 	public static void main(String[] args) {
        Outer outer = new Outer();
        Outer.Inner inner = outer.new Inner();
        inner.in(); // 10 in
    }

Adding the static keyword will become a static internal class. Since the static internal class is created at the beginning of the program, the id cannot be accessed

Anonymous inner class a class without a name

public class Test02{
    public static void main(String[] args) {
        UserService user = new UserService() {
            public void hello() {
                System.out.println("Hello");
            }
        };
    }
}
interface UserService{
    void hello();
}

Topics: Java intellij-idea