Basic features of java

Three characteristics of Java: encapsulation, inheritance and polymorphism

encapsulation

High cohesion and low coupling: the internal data operation of the class is completed by itself, and external interference is not allowed; Try to expose a small amount of methods for external use

Property private, get/set

Meaning of encapsulation:

1. Improve program security and protect data

2. Implementation details of hidden code

3. Unified interface

4. Increased maintainability of the system

Student class:

package oop.Demo03;

//class
//Encapsulation is generally for attributes, and there are few encapsulation methods
//Private: private
public class Student {
    //Property private
    private String name;//name
    private int id;//Student number
    private char sex;//Gender
    private int age;

    //Provide some methods that can operate these properties, and provide some public get and set methods

    //get this data (hump naming)
    public String getName(){
        return this.name;
    }

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

    }

    public void setAge(int age){//Definition rationality
        if(age>120||age<0)
        this.age=3;
        else{
            this.age=age;
        }
    }
    public int getAge(){
        return this.age;
    }

    //Learning ()
    //Sleep ()
}

Application class:

package oop;

import oop.Demo03.Student;

public class Application {
    public static void main(String[] args) {
        Student s1=new Student();
       // s1.name = can no longer pass Operators use these attributes directly

        s1.setName("Zhang San");
        System.out.println(s1.getName());//Zhang San

        s1.setAge(999);
        System.out.println(s1.getAge());//3
    }
}

inherit

  • The essence of inheritance is to abstract a group of classes, so as to realize better modeling of the real world

  • Keyword: extends -- extension. A subclass (derived class) is the inheritance (base class) of the parent class. In a sense, there is a "is a" relationship between the subclass and the parent class

  • In Java, there is only single inheritance, not multiple inheritance. A son has only one father, and a father can have multiple sons

  • In addition to inheritance, the relationships between classes include dependency, composition, aggregation and so on

If a subclass inherits from the parent class, it will have all the methods of the parent class! (public)

private things cannot be inherited

In java, all classes inherit the object class directly or indirectly by default

super note:

super();

1. super calls the constructor of the parent class, which must be in the first place of the constructor

2. super can only be in the subclass method or constructor with Chu Xia'an

3. super and this cannot call construction methods at the same time

The difference between super and this

this("hello");

The objects represented are different:

This: call this function by itself

super: represents the reference of the parent class object

Different premises:

this: it can be used without inheritance

super: can only be used under inheritance conditions

Different construction methods:

this(): the construction of this class

super(): Construction of parent class

Parent class:

package oop.Demo04;
// Person: parent class

//public
//protected
//Default default
//private
public class Person {

    public Person(){

        System.out.println("Person No participation");

    }

    protected String name="zhangsan";

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

Subclass:

package oop.Demo04;

//Student is person: derived class and subclass
public class Student extends Person{

    public Student(){
        //Hidden code: the parameterless construction of the parent class is called: super();
        super();//Calling the constructor of the parent class must be in the first line of the subclass constructor
        //this("hello");
        System.out.println("Student The parameterless construct is executed");
    }
    public Student(String name) {
        this.name=name;
    }

    private String name="zhangwu";

    public void print(){
        System.out.println("Student");
    }
    public void test1(){
        print();//Student
        this.print();//Student
        super.print();//Person
    }

    public void test(String name){
        System.out.println(name);//Zhang Wu
        System.out.println(this.name);//zhangwu
        System.out.println(super.name);//zhangsan in parent class
    }

}

Application:

package oop;

import oop.Demo04.Person;
import oop.Demo04.Student;

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

        Student student=new Student();
//        student.test("Zhang Wu");
//        student.test1();
//        Student s1=new Student();
//        s1.say();// Said a word
//        //System.out.println(s1.money);// report errors
//        Person person=new Person();
    }
}

Method rewrite: (polymorphic)

Rewriting is the rewriting of methods and has nothing to do with properties

Parent class:

package oop.Demo04;

//Rewriting is the rewriting of methods and has nothing to do with properties
public class B {

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

Subclass:

package oop.Demo04;

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

Application:

package oop;

import oop.Demo04.B;
import oop.Demo04.A;
public class Application {

    public static void main(String[] args) {
        //Method is related to the data type defined on the left
        A a = new A();
        a.test();//A

        //The reference (b) of the parent class points to the child class (A)
        B b = new A();//The subclass overrides the method of the parent class
        b.test();//A
    }
}

result:

Static and non static methods are very different:

If the method is changed to static: (it is not rewritten)

package oop.Demo04;

//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 oop.Demo04;

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

import oop.Demo04.B;
import oop.Demo04.A;
public class Application {

    public static void main(String[] args) {
        //Method is related to the data type defined on the left
        A a = new A();
        a.test();//A

        //The reference (b) of the parent class points to the child class (A)
        B b = new A();//The subclass overrides the method of the parent class
        b.test();//B
    }
}

result:
Whether it is rewritten can be seen from the blue circle arrow on the left. It is only rewritten. There is no static method, and it is not changed to private:


Change to private:


Summary:

Rewriting needs to have inheritance relationship, and it is the method of subclass overriding parent class!

1. The method name must be the same

2. The parameter list must be the same (different from overload. Overload is the current method and the parameter list is different)

3. Modifier: the scope can be expanded, but not reduced. Public > protected > Default > private

4. Distinguish from throwing exceptions: the scope can be narrowed, but not expanded. Classnotfoundexception -- > exception (large)

Rewriting means that the methods of the subclass and the parent class must be the same, and the method bodies are different

Why rewrite:

1. The function of the parent class and the subclass are not necessarily required or satisfied

Shortcut: Alt + insert: override

Object oriented Foundation

Keyword (instanceof)

instanceof (type conversion) refers to the type and determines what type an object is

Parent class:

package oop.Demo04;

public class Person {

}

Subclass 1:

package oop.Demo04;

public class Student extends Person{

}

Subclass 2:

package oop.Demo04;

public class Teacher extends Person{

}

Application:

package oop;
import oop.Demo04.*;

public class Application {

    public static void main(String[] args) {

        //Object>String
        //Object>Person>Teacher
        //Object>Person>Student
       Object object = new Student();

       //System.out.println(X instanceof Y);// The success of compilation depends on whether X and y have a parent-child relationship!
        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 errors are reported, which cannot be compared at the same level
        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 errors are reported, which cannot be compared at the same level
    }
}

Conversion between types: parent and child

1. A parent class reference points to a child class object

2. Convert the subclass to the parent class (up, low to high), and directly

3. To convert a parent class to a child class (transition from high to low), you need to force conversion

4. Facilitate method calls and reduce duplicate code

Abstract programming ideas: encapsulation, inheritance, polymorphism! Abstract classes: Interfaces

Paternity is the same as above:

package oop;
import oop.Demo04.*;

public class Application {

    public static void main(String[] args) {
        //Conversion between types: parent and child

        //High and low
        Person obj = new Student();
//        student.go();// Cannot execute

        //Student converts this object to student type, and you can use the method of student type
        //High to low forced conversion
        Student student = (Student) obj;
        student.go();
        ((Student) obj).go();

        //When a subclass becomes a parent class, it may lose some of its original methods
        Student student1 = new Student();
        student1.go();
        Person person = student;//Low to high direct conversion

    }
}

Keyword static

For a class, there is only one static variable in memory, which can be shared by all instances of the class

In a class, static methods can call static methods directly, but non static methods cannot be called

Non static methods can call everything in static methods

package oop.Demo05;

//static
public class Student {

    private static int age;//Static variables are used by multithreading
    private  double score;//Non static variable

    public void run(){
        go();//Non static methods can call everything in static methods
    }
    public static  void go(){

    }
    public static void main(String[] args) {
        Student s1= new Student();//For a class, there is only one static variable in memory, which can be shared by all instances of the class

        System.out.println(Student.age);//0 / / static variables are recommended to be accessed by class name
//        System.out.println(Student.score);// Cannot compile, non static fields cannot be used in this way
        System.out.println(s1.age);//0
        System.out.println(s1.score);//0.0

        Student.go();
        go();//In a class, static methods can call static methods directly, but non static methods cannot be called
//        Student.run();// Compilation failed



    }
}

Static code block:

package oop.Demo05;

public  class Person {

    {
        //Code block (anonymous code block), function: assign initial value
        //There is no name and cannot be called. The class is loaded and run once
        System.out.println("Anonymous code block");
    }

    static{
        System.out.println("Static code block");
        //Static code block, which is executed directly as soon as the class is loaded, and is permanently executed only once
    }

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

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

result:

The class modified by final cannot be inherited:

public final class Person {
}

public class Student extends Person{
}

abstract class

Keywords: abstract

public abstract class Action 

Abstract: Constraints

All methods of an abstract class must implement its methods by subclasses that inherit it

Characteristics of abstract classes:

1. You can't use the abstract class new. You can only rely on subclasses to implement it: constraints

2. Classes with abstract methods must be abstract classes, but ordinary methods can be written in abstract classes

An abstract class cannot be new. Does it have a constructor?

What is the meaning of the existence of abstract classes?

For example, to create characters in the game, each character is very complex and it is very troublesome to create them repeatedly. Just abstract the common attributes and modify their own methods. It can save code and improve efficiency

Abstract class:

package oop.Demo06;

//Abstract abstract class: a class can only inherit single extensions: a single inheritance (only one class can be inherited) interface can realize multiple inheritance
public abstract class Action {

    //Constraints: someone helped us achieve
    //Abstract abstract abstract method, only method name, no implementation
    public abstract void doSomething();

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

}

Subclasses of abstract classes:

package oop.Demo06;

//All methods of an abstract class must implement its methods by subclasses that inherit it
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. Professional constraints! Separation of constraints and Implementation: interface oriented programming

An interface is a specification. It defines a set of rules and is essentially a contract

Keywords: interface

public interface UserService

The differences of common classes, abstract classes and interfaces in software IDEA on icons:


Function of interface:

1. It is a kind of constraint, which can define some methods for different people to implement

2. All methods in the interface are public abstract, and all properties are public static final

3. The interface cannot be instantiated. The interface is not a class and there is no constructor in the interface

4. Class can implement interface keyword: implements interface (can implement pseudo multi inheritance)

5. If you implement the class of the interface, you need to rewrite all the methods in the interface

Interface 1:

package oop.Demo07;

//The keywords defined by interface and interfaces need to have implementation classes
public interface UserService {
    //All defined methods in the interface are actually Abstract public abstract
    public abstract void run();

    //All defined attributes in the interface are constants public static final (constants are generally not defined in the interface)
    public static final int age = 99;

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

}

Interface 2:

package oop.Demo07;

public interface TimeService {
    void time();
}

Application 1:

package oop.Demo07;

//Abstract class: Extensions
//Class can implement interface keyword: implements interface
//If you implement the class of the interface, you need to rewrite the methods in the interface

//Multi inheritance: use interfaces to realize multi inheritance
public class UserServiceImpl implements UserService,TimeService{

    @Override
    public void run() {

    }

    @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 time() {

    }
}

Inner class

Class B is defined in class A. class B is an internal class relative to class A

Use: instantiate the inner class through the outer class

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

Example 1:

Internal class:

package oop.Demo08;

public class Outer {

    private int id;

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

    public void method(){
        class Inner2{//Local inner class, similar to local variables in functions
            public void in(){//Methods in Inner Classes

            }
        }
    }
    
    public  class Inner {//If this is public static class
        // The following getID will not work unless the id is also changed to static
        public void in() {
            System.out.println("This is the method of the inner class");
        }

        //The inner class can obtain the private properties of the outer class
        public void getID() {
            System.out.println(id);
        }

    }
}

Application:

package oop;
import oop.Demo04.*;
import oop.Demo08.Outer;

public class Application {

    public static void main(String[] args) {
        //new

        Outer outer = new Outer();

        //Instantiate the inner class through the outer class
        Outer.Inner inner = outer.new Inner();
        inner.in();



    }
}

Example 2:

(usually not)

package oop.Demo08;

public class Test {
    public static void main(String[] args) {
        Apple apple = new Apple();
        //Class initialization without name - the use of anonymous objects without saving instances to variables
        new Apple().eat();

        UserService userService = new UserService(){
            public void hello(){

            }
        };

    }
}

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

interface UserService{//Interface
    void hello();
}

Keywords: Java IntelliJ IDEA Back-end

Added by McMaster on Fri, 28 Jan 2022 16:07:14 +0200