03Java object oriented

Process oriented and object-oriented design ideas

Process oriented: is a programming idea. C language

When solving problems, it is implemented step by step according to specific implementation steps.

Process oriented, direct attention to process.

eg. open the door first ()

Second, install elephants ()

Final closing ()

Object oriented: is a programming idea. Java,Python,C++,C#

Think and solve problems in a classified way.

First, classify the overall relationship, and deal with the details according to different classes.

In line with human cognitive habits.

  • Object oriented - > use what objects are and where objects come from

  • Object oriented implementation: classify objective things (design classes / discovery classes are abstract). In actual use, you need to create specific objects with classes as templates.

    Human - > Zhang San (object)

    Design a refrigerator class (Abstract)

    public class refrigerator{

    Name

    Model

    Price

    Open the door ();

    Loading elephants;

    Close the door ();

    }

    Refrigerator bx = new refrigerator ()// bx represents this object. At runtime, a space will be set aside in memory to store specific objects.

    bx. Open the door ()// Specific object

    Refrigerator. Open the door ()// Wrong refrigerator is a concept

Object oriented is to design the relationship between things on the macro whole, and the specific implementation returns to the specific implementation of process oriented. The two complement each other.

What is a class

Class is a template, which abstracts the attributes (nouns) and behaviors (verbs) of the same kind of things.

Class has an address, and the package is its address.

Class is a template, which is

Class structure:

  • Member variable: a description of the attributes of a thing. Noun attribute

    Member variables can be initialized or not initialized when they are defined. java will assign them by default in the construction method. Reference type value: null int: 0 float: 0.0 char: 'boolean: false

    Local variables need to be initialized by themselves.

    When an object is created, a copy of the member variable is copied from the class to the object

    Member variables can be accessed by methods, construction methods, and code blocks

  • Member method: the behavior of things. (something that can be done) verb action

  • Construction method: initialize the object. Initialization object with full-time function

  • Inner class: the class declared in the class body.

  • Code block: a piece of code without a name.

Class definition:

  • Discovery class
  • Find common properties (member variables) of the class
  • Methods for discovering classes

Create objects using classes as templates.

Everything (the concrete things that actually exist) is the object

//Car.java

/*Discovery car
* public(Access modifier class (keyword modifier class) Car (class name)
* {
*      Class body
*      Member variable
*      Member method
*      Construction method
* }*/
public class Car {
    /*
        Defines the member variable noun property of a class
        It is directly defined in the class, so it becomes a member of the class
        You can use any data type, basic type and reference type supported by java
    */
    String name;  //reference type
    String color;
    float price;  //Basic type

    /*
        Defines the member method verb behavior of a class
    */
    public void run(){
        System.out.println(this.name+"Car driving");
    }

    public void stop(){
        System.out.println(name+"Car stop");
    }

}

What is an object

An object is an instance of a class. It is an actual instance created in memory with a class as a template.

//TestCar.java

public class TestCar {
    public static void main(String[] args) {
        /*
            A class is a template, an abstract concept, and a definition
            Objects are concrete and can be used directly. They are actual instances created in memory with classes as templates
        */
        Car bm = new Car();
        bm.name = "bmw";
        bm.color = "black";
        bm.price = 200000;
        System.out.println(bm.name);
        bm.run();
        bm.stop();

        Car bc = new Car();
        bc.name = "Benz";
        bc.color = "black";
        bc.price = 2043000;
        System.out.println(bc.name);
        bc.run();
        bc.stop();
    }
}

Object creation and use:

  • Car bm = new Car();

  • Car() constructor. The constructor has the same name as the class name. Use the new Car() new keyword to create an object.

    Take the Car class as the template, create a specific instance in memory, and copy the members of the class template to the specific object. Each object is unique.

  • Car bm/bc declares a variable of type car.

  • =Assign the object address on the right to the variable on the left, which represents the object in memory in the program.

  • Each object of the same class has different member variable storage space.

  • Each object of the same class shares the methods of that class.

Classes and objects

Class is an abstract concept of a class of things and a model.

Objects are concrete and real instances created by this model. Therefore, the process of creating an object is also called instantiating an object.

In real life, there are objects before classes, and when programming, design classes before creating objects.

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-T07lZ2qF-1642687013926)(E:\Java learning \ 2022-1-16java Chapter III object-oriented 1 \ courseware \ create object diagram. png)]

Construction method

Features: the constructor name is the same as the class name, and there is no return value, and void modification is not required.

Function: initializes and assigns values to the created object in the constructor.

Each time an object is created, at least one constructor must be called, and there can be multiple constructors in a class

Each class has a constructor. If you do not explicitly define a constructor for a class, Java will provide a default constructor for the class, but as long as a constructor is defined in a Java class, the default parameterless constructor will become invalid.

A class can have more than one constructor.

//Car.java

public class Car {

    String name;
    String color;
    float price;

    /*
       The default parameterless construction method in the class is available by default,
       If no displayed is written out, and if a construction method with parameters is defined, the non parametric will be overwritten
       In general, after defining the construction method with parameters, it is best to define the display without parameters
    */
    public Car(){
        //In the parameterless constructor, you can use the default value to assign values to the properties in the object
        //Reference type: null integer: 0 floating point: 0.0 char: 'boolean:false
    }

    public void run(){
        System.out.println(this.name+"Car driving");
    }

    public void stop(){
        System.out.println(name+"Car stop");
    }

}
//TestCar.java
public class TestCar {
    public static void main(String[] args) {
        /*
            new Car()  ---> Construction method
            Features: the construction method name is the same as the class name, and there is no return value, and void modification is not required
            Function: initializes and assigns values to the created object in the constructor
            Each time an object is created, at least one constructor must be called, and there can be multiple constructors in a class
        */
        Car bm = new Car();
        bm.name = "bmw";
        bm.color = "black";
        bm.price = 200000;
        bm.run();
    }
}

Method overload

There are multiple methods with the same name in a class.

Constructor and member methods can be overloaded.

How to distinguish methods:

  • Distinguish by the number of method parameters
  • Distinguish by type
  • Distinguish by order

When calling, the corresponding method will be selected according to different parameter tables.

Note: method overloading has nothing to do with the return value type of the method.

Function of overload: extend method function.

//Construction method
public Car(){
    //In the parameterless constructor, you can use the default value to assign values to the properties in the object
    //Reference type: null integer: 0 floating point: 0.0 char: 'boolean:false
}

public Car(String name,String color,float price){
    //this indicates the object currently in use
    this.name = name;  //This name is the name in the member variable
    this.color = color;
    this.price = price;
}
//Construction method
public Car(String name,String color){
    this.name = name;  //This name is the name in the member variable
    this.color = color;
}

public Car(float price,String name,String color){
    //this indicates the object currently in use
    this.name = name;  //This name is the name in the member variable
    this.color = color;
    this.price = price;
}
//Member method
public void run(){
    System.out.println(this.name+"Car driving");
}

public void run(int speed){
    System.out.println(this.name+"Car to"+speed+"Speed travel");
}
public class TestCar {
    public static void main(String[] args) {
        Car bm = new Car();
        bm.name = "bmw";
        bm.color = "black";
        bm.price = 200000;
        bm.run();

        Car bc = new Car("Benz","gules",300000);
        bc.run();

        Car dz = new Car("public","gules");
        dz.run(120);
    }
}

Objects and references

Except for the eight basic types in java, the rest are reference types.

Basic type: keyword declaration, simple structure.

int a = 10;

Reference type: class, array, structure

Class is a conforming type, which is more complex and can define more things

Car dz = new Car("public","gules");

Car ad = dz; //Two objects ad and dz are created to point to the same object
ad.name = "audi";
System.out.println(ad.name);  //audi
System.out.println(dz.name);  //audi
System.out.println(bc.name);  //Benz

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-Desjw9nZ-1642687013933)(E:\Java learning \ 2022-1-17java Chapter III object-oriented 2 \ courseware \ object creation memory map. png)]

Value passing and reference passing

Strictly speaking, parameter passing is only value passing

In order to distinguish between basic types and reference types, it is divided into value passing and reference passing

  • Value passing refers specifically to basic types.

    When a method is called, the actual parameter passes its value to the corresponding formal parameter. The formal parameter only initializes its own storage unit content with the value of the actual parameter, which is two different storage units. Therefore, the change of the formal parameter value during method execution does not affect the value of the actual parameter.

    public class TestValue {
        public static void main(String[] args) {
            int a = 10;
            TestValue t = new TestValue();
            t.test(a);
            System.out.println("a:"+a);  //What is the value of a? ten
        }
    
        /*
            The basic type is value passing
        */
        public void test(int b){
            System.out.println("b:"+b);  //10 
            b = 20;
        }
    }
    
  • Reference passing corresponds to a reference type.

    Also known as a forwarding address. When a method is called, the actual parameter is an object. At this time, the actual parameter and the formal parameter point to the same address. During method execution, the operation on the formal parameter is actually the operation on the actual parameter. This result is retained after the method is completed, so the change of the formal parameter during method execution will affect the actual parameter.

    public class TestValue {
        public static void main(String[] args) {
            TestValue t = new TestValue();
            Car car1 = new Car();
            car1.name = "Benz";
            t.test(car1);
            System.out.println("car1.name:"+car1.name);  //public
        }
    
        /*
            The reference type passes not the object itself, but the reference address of the object
        */
        public void test(Car car2){
            System.out.println("car2.name:"+car2.name);  //Benz
            car2.name = "public";
        }
    }
    
    

The basic type passes the data value itself. A reference type passes a reference to an object, not the object itself.

this keyword

The this keyword represents the object currently in use.

static keyword

Static is called static and can be used to modify class properties, methods, code blocks and internal classes.

  • Loads as the class loads
  • Prior to object existence
  • Decorated members that are shared by all objects
  • It can be called directly by the class without creating an object.

Static attributes are shared by all objects of the class, that is, no matter how many objects are created, there is only one static attribute in memory.

public class Aodi {
    /*
       Aodi Their names should be Audi, and they should be assigned directly when defining classes.
            The model and price are different
    */
    String model;
    float price;
    //There is only one member variable modified by static in memory. All objects can be shared and loaded with the loading of the class. It is called through the class name
    static String name = "audi";
}

public class TestAodi {
    public static void main(String[] args) {
        
        System.out.println(Aodi.name); //You can be called directly by a class without creating an object

        Aodi a8 = new Aodi();
        a8.model = "a8";
        a8.price = 300000;
        System.out.println(Aodi.name+":"+a8.model+":"+a8.price); //It can be called directly through the class name

        Aodi q8 = new Aodi();
        q8.model = "q8";
        q8.price = 500000;
        System.out.println(q8.name+":"+q8.model+":"+q8.price);
    }
}

static method can be called by object or directly by class name. It is recommended to call directly by class name.

In the static method, you can only access the static attribute of the class, not the non static attribute of the class. The static attribute is loaded first.

After the static members are loaded with the class, they can be used. Instead of static, you must create an object before you can use it.

//The static modified method is a static method. It belongs to a class and can only use static member variables.
public static void run(){
    System.out.println(name);
    System.out.println(this.model); //An error is reported. It can only be used after a non static object is created
}

//Can be used directly
Aodi.run();

Code block

A code block is declared in a class, similar to a method body without a name.

Class is automatically executed when it is loaded.

It is divided into instance code block and static code block.

  • Instance code block: called when an object is created.
  • Static code block: called only once when the class is loaded (because the class is loaded only once).
{
    System.out.println("Example code block 1");
}
{
    System.out.println("Example code block 2");
}
/*
   Later, the content that needs to be executed automatically when the class is loaded is written in the static code block and executed only once
*/
static {
    System.out.println("Static code block 1");
}
static {
    System.out.println("Static code block 2");
}

public class Test {
    public static void main(String[] args) {
        new Aodi();  //Create the object for the first time and load the class
        new Aodi();  //Create the object for the second time without loading the class
    }
}

//Static code blocks are limited and executed once.
//Reason: analogy objects are loaded first and only once
/*The output result is:
Static code block 1
 Static code block 2
 Example code block 1
 Example code block 2
 Example code block 1
 Example code block 2
*/

package

Package: in order to better manage classes in java, create a package for management, which is used to distinguish the namespace of class names.

A package is actually a folder on the hard disk, but it is different from a file in a java project. It exists as a class path.

directory: folder package: package

There will not be two same class names under the same package.

Function of package:

  • Avoid duplicate class names (distinguish between duplicate classes)

    package Day3;
    
    //When importing classes from other packages, you need to import classes from other packages (classes from the same package and java.lang packages do not need to be imported)
    import Day2.Car;
    
    public class Test {
        public static void main(String[] args) {
            String s;  //java.lang package
            /*
               Car Is the abbreviation of the class. The full name of the class (full class name) day2 Car
            */
            new Car();  //Car in Day2 bag
            new Day1.Car();  //The Car in Day2 has been imported. Only the full class name can be used
    
    
        }
    }
    
    
  • Manage classes according to different functions

    eg. control layer, data access layer, business logic processing layer, public class, configuration class, tool class, etc

  • Control access

    Access modifier (see next title)

Package naming convention: in the package name, you can use The package name is generally lowercase.

  • The first level refers to the type of the project, such as com (business company), org (Organization), gov (government), edu (Education), etc,
  • The second level refers to the name of the company where the project is developed or operated, such as oracle,sun,huawei, etc
  • The third level refers to the name of the project, such as bcms,oa,erp,cms, etc
  • The fourth level refers to the name of the project module, such as bean,action,exception, etc

Access modifier

Manage classes according to different functions

Control access

The Java language has four permission access modifiers, which are in descending order:

  • Public: public permission modifies classes, attributes and methods. Can be accessed by any class
  • Protected: protected permission modifies attributes and methods. It can be accessed by the same package class. If it is not the same package class, it must be a subclass of this class.
  • default: same package permission modifies classes, attributes and methods. Can only be accessed by classes in the same package
  • Private: private permission modifies attributes and methods. Can only be accessed in this class

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-ubA98y4u-1642687013940)(E:\Java learning \ access right modifier. png)]

package com.ffyc.javaoop.day3;
    /*
       Class can only be decorated with public and default
    */
public class Demo {
    /*
       public Public permissions can be accessed in any class
       protected Protected permissions can be accessed in their own classes, in other classes of the same package, and in subclasses of different packages
                 The default permission is in your own class and in other classes of the same package
       private   Private permissions can only be accessed in their own classes
    */

    public String pubName;
    protected String proName;
    String delname;  //default
    private  String priName;

    protected  void test1(){

    }
    protected void test2(){


    }
    void test3(){

    }
    private void test4(){
        
    }
    
    public void test(){
        Demo d = new Demo();
        d.pubName = "p";
        d.proName = "po";
        d.delname = "";
        d.priName = "pi";
    }
}
package com.ffyc.javaoop.day3.child;

import com.ffyc.javaoop.day3.Demo;

public class ChildDemo extends Demo{
    public void test(){
        Demo d = new Demo();
        d.pubName = "a";  //Only public is left

        ChildDemo cd = new ChildDemo();  //Default and private permissions are still inaccessible
        cd.proName = "1";
        cd.pubName = "q";
    }
}
package com.ffyc.javaoop.day3;

public class Demo1 {
    public void test(){
        Demo d = new Demo();
        d.pubName = "a";
        d.proName = "p";
        d.delname = "d";
    }
}

Three characteristics of object oriented

Three characteristics of object-oriented language:

  • encapsulation
  • inherit
  • polymorphic

encapsulation

Encapsulation: encapsulating a function into a method. eg. wrote a tool class and defined several common methods.

Encapsulation in object-oriented: hiding (access modifiers private, protected, default, public...) keeps some information in the class from being opened to the public.

private String name;  //Property privatization is just a representation of encapsulation

Package features:

  • Hide class implementation details
  • Easy to add control statements
  • It can only be accessed through specified methods
  • Convenient modification and Implementation
package com.ffyc.javaoop.day3.pack;

public class Person {
    private String name;
    private int age;

    public void setAge(int age){
        if(age>18){
            this.age = age;  //this.age in age object
        }
    }

    public int getAge(){
        return age;
    }

    //The setXXX method is a public method that provides access to private properties
    public void setName(String name){
        //Easy to add control statements
        if(name.length()>3 && name.length()<6){
            this.name = name;
        }
    }

    public  String getName() {
        return this.name;
    }

}
package com.ffyc.javaoop.day3.pack;

public class TestPerson {
    public static void main(String[] args) {
        //private hides the name attribute and cannot be accessed in other classes
        Person zs = new Person();
//        zs.name = "fadsf";
        zs.setName("fsdfj");
        System.out.println(zs.getName());
    }
}

Singleton mode: (a mode is a template. If you solve a problem, you have)

Singleton mode solves that only one class can create one object in a program.

package com.ffyc.javaoop.day3.pack;

public class WindowDemo {
    static WindowDemo windowDemo = null;

    /*
       Privatize the constructor so that objects cannot be created in other classes
    */
    private WindowDemo(){

    }

    //Provide a method to create a unique object and return it
    public static WindowDemo getWindowDemo(){
        //Singleton mode
        //The first time it has been created, the second time windowDemo is not null, so it directly returns windowDemo
        if(windowDemo == null){
            windowDemo = new WindowDemo();
        }
        return windowDemo;
    }
}
package com.ffyc.javaoop.day3.pack;

public class TestWindow {
    public static void main(String[] args) {
//        new WindowDemo();  Cannot create object because constructor is private
        System.out.println(WindowDemo.getWindowDemo());
        System.out.println(WindowDemo.getWindowDemo());
    }
}

inherit

Inheritance is an indispensable design idea in object-oriented programming. It is the main way to realize code reusability and improve code scalability.

When to use inheritance:

  • You can extract some common attribute behaviors and create a parent class for other classes to inherit.

    eg. cats are animals, dogs are animals, and they belong to the same class

Basic syntax:

  • Parent - > child
  • Subclass extends parent class extends Object
public class Animal extends Object{
    private String name;
    private int age;

    public void eat(){
        System.out.println(this.name+"Animals eat");
    }

    //The get set method is used exclusively for private property assignment
    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}


/*
   The subclass inherits from the parent class and uses the extends keyword
   A class can inherit only one parent class directly, but it can inherit indirectly
*/
public class Dog extends Animal{

}


public class AngelDog extends Dog{
    //Expand the function of bytes and call the function of the parent class repeatedly at the same time
    public void fly(){
        System.out.println("A howling dog can fly");
    }
}
public class Test1 {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.setName("cocoa");
        dog.setAge(5);
        System.out.println(dog.getName());
        System.out.println(dog.getAge());
        dog.eat();
    }
}

Inheritance is to derive a new class from an existing class. The new class can absorb the properties and behavior of the existing class and expand new capabilities.

  • In JAVA, the extends keyword is used to represent the inheritance relationship.
  • JAVA does not support multiple inheritance. Single inheritance makes the inheritance relationship of JAVA very simple. A class can only have one direct parent class.
  • After inheritance, the subclass can call all non private properties and methods of the parent class

Designs that conform to the is-a relationship use inheritance. Put the properties and behaviors shared by subclasses into the parent class.

Transitivity of inheritance:

  • If class C inherits from class B and class B inherits from Class A, class C has all non private properties and non private methods of class B and class A.
  • When a class that is not displayed inherits any class, the jvm will let the class inherit the object class by default. Object (java.lang package) is the base class (parent class / superclass) of all classes.

Construction method in inheritance:

  • When you create an object and call the constructor, the constructor of the child class will call the constructor of the parent class by default. Because the parent class must be initialized before the child class can use the attribute behavior in the parent class.

    Constructor can be used to initialize

  • Calling any constructor of the parent class with the super keyword must be written in the first line of the constructor.

  • If the base class constructor is not explicitly called in the constructor of the subclass, the system will call the constructor of the base class without parameters by default.

    public class AngelDog extends Dog{
        //Expand the function of bytes and call the function of the parent class repeatedly at the same time
        public void fly(){
            System.out.println("A howling dog can fly");
        }
    
        public AngelDog(){ //super represents a parent class, not a parent object
            //super () calls the parent class constructor. It exists by default and can not be written. It is in the first line of the child class constructor
            //If a call is displayed, it must be called on the first line
            super(); 
            System.out.println("AngelDog Class nonparametric construction");
        }
    }
    

super keyword purpose:

  • Use the super keyword to access parent class members.

  • Use super Member variable name to reference the parent class member variable.

  • Use super Method name (parameter list) the method that accesses the parent class.

  • Use super Constructor (parameter list) accesses the parent constructor.

  • Note: do not mistake super for a parent object When creating a subclass object, the parent object will not be created, and only the information in the parent class will be loaded into the subclass object for storage.

    public AngelDog(){  //super represents the parent class
        super();
        System.out.println("AngelDog Class nonparametric construction");
        super.eat();
    }
    

Method Rewriting: when the method implementation of the parent class cannot meet the needs of the child class, the method can be overridden.

  • Rewriting requirements: consistent with the method name in the class, consistent with the parameters and return values, and the access permission is equal to or greater than the permission of the parent class.

  • @Override is marked by the annotation tag in java. It acts on a method to indicate that the method is overridden from the parent class and detects the syntax format during compilation.

    /*
    The implementation of divine dog eating is different from that of other animals, so you can override (override) the eat () method in the Animal class in the howling Dog class
     Rewriting requirements: consistent with the method name in the parent class, consistent with the parameters and return values, and the access permission is equal to or greater than the permission of the parent class
    
    @Override Is an annotation tag in java, which is used to mark
    @Override It acts on a method, indicating that the method is overridden from the parent class and detects the syntax format during compilation.
    */
    @Override
    public void eat(){
        System.out.println("The dog sat eating");
    }
    

polymorphic

The same thing shows different states at different times.

Premise: there must be inheritance (including interface implementation), method rewriting, and the reference of the parent class points to the subclass object.

//The reference of the parent class points to the child class object
Animal dog1 = new Dog();
Animal cat1 = new Cat();
Object d = new Dog();

Dog dog = new Dog();  //The Dog reference points to the Dog object
Cat cat = new Cat();  

During compilation: when writing code, it is during compilation. Animal dog1 is of type animal during compilation.

During run: run the program. Animal dog1 is a Dog type during runtime.

For member methods, compile to the left and run to the right.

Object is created at run time.

[the external chain picture transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-JD3FJj9a-1642687013942)(E:\Java learning \ 2022-1-19java Chapter III object-oriented 4 \ courseware \ Snipaste_2022-01-19_11-26-24.png)]

For static methods, both compilation and operation are on the left.

For member variables, the compilation and operation are shown on the left.

Polymorphism: it improves the extensibility of the program, so the subclass type is changed upward to the parent type.

Polymorphism has disadvantages: when using polymorphism, you cannot access the unique methods in the subclass, because it has been converted to the parent type, and the unique methods of the subclass cannot be called during compilation.

Solution: you need to make a downward transition. Before the transition, you'd better judge the type and use the instanceof keyword.

public class Test2 {
    public static void main(String[] args) {
        /*
           Create a function of feeding different animals and eating animals.
           It is not implemented by polymorphism, and the scalability is not good.
        */
        Dog dog = new Dog();
        Cat cat = new Cat();

        Test2 t = new Test2();
        t.feedDog(dog);
        t.feedCat(cat);
    }

    public void feedDog(Dog dog){
        dog.eat();
    }

    public void feedCat(Cat cat){
        cat.eat();

    }
}
public class Test3 {
    public static void main(String[] args) {
        /*
           Create a function that feeds different animals and animals eat.
           It is realized by polymorphism.
           By raising the subclass type to the parent type, you can use the parent type to represent all subclass objects (the benefit of polymorphism)
        */
        Animal dog = new Dog();
        Animal cat = new Cat();

        Test3 t = new Test3();
        t.feedAnimal(dog);
        t.feedAnimal(cat);
    }

    public void feedAnimal(Animal animal){
        animal.eat();
//        animal. play();   There is no play () method in animal, so an error is reported and a downward transformation is required
//        Dog dog = (Dog) animal;
//        dog. play();  // There is no play () in cat class, so cat reports an error
        //You need to make a judgment when you type down
        //Key: instanceof checks whether the actual type of animal is Dog when running. If yes, it returns true; otherwise, it returns false.
        if(animal instanceof Dog){
            Dog dog = (Dog)animal;
            dog.play();
        }
    }
}

abstract class

Abstract is a concept, not concrete.

Abstract method:

  • Abstract method is a special method: it has only declaration, but no concrete implementation.
  • Abstract methods must be decorated with the abstract keyword.
  • In some systems with large architecture, the methods in the top-level classes can be defined as abstract.

Abstract class:

  • If a class does not contain enough information to describe a specific object, such a class is an abstract class.

  • In addition to not instantiating objects, abstract classes still have other functions, such as member variables, member methods and construction methods.

  • A class decorated with abstract is an abstract class. If a class contains abstract methods, the class must be defined as an abstract class

    /*
       If there are abstract methods in a class, the class name must be an abstract class
       But there are not necessarily abstract methods in abstract classes
       An abstract class is an incomplete class with abstract methods
       Abstract classes cannot create objects because they do not have concrete abstract methods. Except that they cannot create objects, other functions of abstract classes are consistent with those of normal classes.
    */
    public abstract class Animal {
        private  String name;
        int age;
    
        /*
           abstravt The modification method is an abstract method, which can have no concrete implementation
           Just as the definition of a function, it is often only necessary to define the function in the top-level class and let other classes implement it
        */
        public abstract void eat();
    
        public Animal(){
    
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    }
    
    /*
       A class inherits an abstract class and can continue to be declared as an abstract class
    */
    public abstract class Dog extends Animal{
        private String type;
    
        public String getType() {
            return type;
        }
    
        public void setType(String type) {
            this.type = type;
        }
    }
    
    /*
       Xiaotian dog is a concrete class that overrides the abstract methods in the parent class
    */
    public class AngelDog extends Animal{
        @Override
        public void eat(){
            System.out.println("The dog sat eating");
        }
    }
    
    public class Test {
        public static void main(String[] args) {
            AngelDog xtq = new AngelDog();
            xtq.setAge(1000); //Non idle can still be called
            xtq.eat();
        }
    }
    

Abstract class features:

  • Abstract classes cannot be instantiated, but they can have constructors. Because abstract classes contain methods without concrete implementation, objects cannot be created with abstract classes.
  • Abstract classes can only be used as base classes, representing an inheritance relationship. A non abstract class that inherits an abstract class must implement all the abstract methods in it. The parameters and return values of the implemented methods must be the same as those in the abstract class. Otherwise, the class must also be declared abstract.

final keyword

final is used to declare properties, methods, and classes.

  • Attribute: the attribute modified by final is a constant, the value cannot be changed, and the assignment must be initialized.

    //When defining, it is assigned directly, and the value cannot be changed. static assignment is recommended. There is only one value in the whole memory.
    static final int num = 100;
    //At the time of definition, the constant is not assigned a value, which must be assigned in the constructor. In each object, you can have a constant.
    final int count;
    //Create a construction method with parameters
    public finalDemo(int count) {
        this.count = count;
    }
    
    public void test(){
    //        num = 10;  //final modifier cannot be assigned
        new String("abc");
        //An object is assigned a value in its constructor only when it is created.
        new finalDemo(10);
        new finalDemo(20);
    }
    
  • Methods: final modified methods cannot be overridden by subclasses and cannot modify abstract methods.

    public final void test(){
        //Methods decorated with final cannot be overridden by subclasses
    }
    
  • Class: modified classes cannot be inherited, and final cannot modify abstract classes and interfaces.

Interface

Interface (USB interface): focus on the design of functions rather than implementation. Let other classes implement it concretely. Similar to abstract classes, but different.

Basic syntax:

  • All attributes in the interface are public static final static constants by default
  • Abstract method default: public abstract modifier
  • After jdk8, static methods are added, and the interface can be called directly.
  • After jdk8, the default method is added and called through subclasses.
public interface Myinterface {

//    public static final int NUM = 10; // You must assign a num constant, which is preceded by public static final by default
    int NUM = 10;  //The default attribute of an interface definition is a static constant

//    public abstract void eat();   The previous default is the public abstract modifier
    void eat();
    void sleep();

    //After Java 8, two new methods (static method and default method) are added
    //Static method interface calls itself
    public static void test1(){
        System.out.println("test1 "+NUM);
    }
    //The default method is to let subclasses override or let subclasses call
    public default void test2(){
        System.out.println("test2");
    }
}

public class Test {
    public static void main(String[] args) {
        System.out.println(Myinterface.NUM);
        Myinterface.test1(); //Static method
//        Myinterface.test2();   The default method cannot be called directly
    }
}

Interface inheritance:

  • A class can inherit only one class directly
  • A class can implement multiple interfaces
  • An interface can inherit multiple interfaces
public class MyinterfaceImpl extends Object implements Myinterface,InterfaceC{
    //Myinterfaceimpl: name of myinterface class and implementation of Impl interface

    //Static methods cannot be overridden. The default method can be overridden or not
    /*
       A class implements the interface, or continue to declare this class as an abstract class; Or rewrite all abstract methods in the interface.
    */
    @Override
    public void eat() {

    }

    @Override
    public void sleep() {

    }
    //The default method can be overridden or not
    @Override
    public void test2() {

    }
}

public interface Myinterface extends InterfaceA,InterfaceB{}

Characteristics of interface:

  • Interfaces are implicitly abstract. When declaring an interface, you do not need to use the abstract keyword
  • Methods in interfaces can be abstract, static, and default
  • The properties declared in the interface are public static final by default
  • Interfaces are not inherited by classes, but implemented by classes
  • Interface cannot instantiate object, no constructor
  • A class can implement multiple interfaces
  • Similar to inheritance, there is polymorphism between interface and implementation class
  • One interface can inherit multiple other interfaces
  • When a class implements an interface, the class implements all the abstract methods in the interface. Otherwise, the class must be declared abstract

The difference between abstract classes and interfaces

Similarities:

  • Cannot create objects
  • Can represent polymorphism

difference:

  • Interface
    • Interface cannot have constructor
    • Cannot have member variables
    • Cannot have member methods, only static methods and default methods
  • abstract class
    • Can there be a construction method
    • Can have member variables

When to use interfaces and abstract classes:

public abstract class Animal {
    private String name;

    public Animal(){

    }

    public Animal(String name ){
        this.name = name;
    }

    public abstract void eat();

    public abstract void sleep();

    public String getName() {
        return name;
    }

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

public class Bird extends Animal implements CanFly,CanCry{
    @Override
    public void eat() {

    }

    @Override
    public void sleep() {

    }

    @Override
    public void cry() {

    }

    @Override
    public void fly() {

    }
}

public class Dog extends Animal{
    @Override
    public void eat() {

    }

    @Override
    public void sleep() {

    }
}

public interface CanCry {
    void cry();
}

public interface CanFly {
    void fly();
}

public class Test {
    public static void main(String[] args) {
        Animal bird = new Bird();
        CanFly b = new Bird();  //Interfaces can also exist as parent types
        CanCry c = new Bird();
//        CanCry d = new Dog();  Dog has no cancry interface and cannot be implemented
    }
}

Keywords: Java Back-end

Added by yuan22m on Sat, 22 Jan 2022 05:07:05 +0200