编程知识 cdmana.com

To be a better javaer -- Java basics Vol.2: object oriented

Java Is an object-oriented high-level programming language , Object oriented features are as follows :

  • Object oriented has abstract 、 encapsulation 、 Inherit 、 polymorphic Other characteristics ;
  • Object oriented can simplify complex business logic , Enhance code reusability ;
  • Object oriented is a common idea , More in line with people's thinking habits .

What is process oriented and object-oriented ?

  1. The sequential execution of a program is a function oriented process , Every function is realized step by step .
  2. Object oriented is to make function 、 Transaction highly abstract programming ideas , Break the problem down into many steps , Every step has to be abstract , To form an object . By calling different objects , To solve the problem .

The difference between the two

  1. Process oriented is a top-down design pattern , Consider that each module should be decomposed into sub modules , Each sub module has to be decomposed into smaller sub modules , Until the module is broken down into functions ( Or the method ). The smallest unit of procedure oriented program is function , Each function is responsible for completing a function , Used to receive input data , Function to process , Output results .
  2. The smallest object-oriented program unit is a class , When the software system is huge , Easy to maintain

object & class

In most object-oriented languages class Defining classes , A class is an abstraction of a series of objects , Class is like the outer packing of express delivery , The content in the class represents the definition of the object ; for example :

class Javaer{
 
}

such , I declared a name as Javaer Class , stay Java in , Can pass new To create this object :

Javaer javaer = new Javaer();

stay Java in , The naming of a class should follow Hump nomenclature ,

Camel nomenclature (Camel-Case) It is also called hump nomenclature , It is a set of naming rules for computer programming ( practice ). As its name is CamelCase It means that , It's a mixture of uppercase and lowercase letters to form the names of variables and functions . Programmers can communicate with each other more easily for their own code , Therefore, we should adopt a unified and readable naming method .

Create objects

In the use of Java In the process , It's all about dealing with people ,Java Everything in can be regarded as an object , But nonetheless , We manipulate objects , It's about the object quote :

Door key;

The code above creates only references , Not an object ; If you want to create an object correctly and don't make mistakes during compilation , Then you need to assign an object to it when creating an object reference .

Door key = new Door();

stay Java in , Once a reference is created , Just hope it can be associated with a new object , Usually use new Operators to achieve this .

Properties and methods

For a class , The basic element is to have attribute and Method ;

Properties are also called fields :

Class Door {
 int a;
 Key key;
}

The method is the function , The basic components of the method include Method name 、 Parameters 、 Return value and method body

public int get(){
 return 1;
}

In the example above ,get It's the method name ,() Is the parameter received by the method 、return The following is the return value of the method ( If it is void Method , No return value is required ),{} In it is the method body .

Construction method

Java There is a special Construction method , It's also called a constructor or constructor . Constructor is to ensure that each object is initialized when creating objects . The constructor is called only once when the object is created , It has no parameter type and return value , Its name should be consistent with the class name , And there can be more than one construction method .

Class Door{
 int number;
 String color;
 
 public Door(){}
 public Door(int number){}
 public Door(String color){}
 public Door(int number,String color){}
}

The code above defines a Door class , But there is no parameter type and return value , And there are multiple names Door() Method , Each method has a different parameter list , This is actually object-oriented -- polymorphic The embodiment of , It will be introduced later . After defining the construction method , We can create a Door Object .

class creatDoor{
 public static void main(String[] args) {
 Door door1 = new Door();
 Door door2 = new Door(1);
 Door door3 = new Door("yellow");
 Door door4 = new Door(1,"yellow");
 }
}

If there is no constructor defined in the class , that JVM Will automatically generate a constructor for you , as follows

class Door {
  
  int number;
  String color;
  
}

class createDoor {

    public static void main(String[] args) {
        Door door1 = new Door();
    }
}

The default constructor is also known as the default constructor or parameterless constructor .

One thing to note here is that , Even if JVM A parameter free constructor will be added for you by default , But if you define any constructor manually ,JVM No more default constructors for you , You have to specify... Manually , Otherwise, there will be compilation errors .

Method overloading

Heavy load in Java Is a very important concept , It's a different representation of a class name , The constructor mentioned above , It's a heavy load , Another overload is method overloading .

public class Door {

    int number;
    String color;

    public Door(){}
    public Door(int number){}
    
    public int getDoor(int number){
        return 1;
    }
    
    public String getDoor(String color){
        return "color";
    }

}

As shown above , Yes Door Overload of constructor of , Also have getDoor Method overloading .

If there are several identical method names ,Java How to know which method you are calling ?

Each overloaded method has a unique parameter list . This includes the type of parameter 、 The order 、 Number of parameters, etc , Satisfying one factor constitutes a necessary condition for overloading :

  • The method name must be the same .
  • Parameter list must be different ( The number is different. 、 Or of different types 、 Parameter types are arranged in different order ).
  • Methods can have the same or different return types .
  • It's not enough to be an overload of a method just because the return type is different .
  • Overloading occurs at compile time , Because the compiler can choose which method to use depending on the type of parameter .

Method rewrite

The description of method rewriting is to Children and parents Between .

Overloading occurs in the same class .

class Food {
 
    public void eat(){
    System.out.printl('eat food');
  }
}

class Fruit extends Food{
  
  @Override
  public void eat(){
    System.out.printl('eat fruit');
  }
}

In the above code , There are examples of rewriting , Subclass Fruit Methods and superclasses in Food The same way

So the standard for rewriting is :

  • The overridden method must be consistent with the parent class , Include return type , Method name , parameter list It's all the same .
  • The method of rewriting can use @Override Annotate to identify
  • The access permission of overriding method in subclass cannot be lower than that of method in parent class .

initialization

We're creating an object , Use new When creating objects , In fact, this object is initialized by calling the construction method without parameters . This parameterless constructor can hide , from JVM Automatic addition . in other words , The constructor ensures the initialization of the class .

class Door{
  public Door(){}
}

Member initialization

There are two forms of member initialization

  1. The compiler initializes the fields specified by default , Initialization of basic data types
type Initial value
boolean false
char /u0000
byte (byte)0
short (short)0
int 0
long 0L
float 0.0f
double 0.0d

Other data types , Such as String , The default value is null

  1. The initialization of the specified value
int a = 11;

Constructor initialization

Constructors can be used to initialize certain methods and actions , So as to determine the initial value :

public class Number{
  int n;
  public Number(){
    n = 11;
  }
}

Using constructors , Can handle n The value of is initialized to 11.

Initialization sequence

  • Static attribute :static Properties defined at the beginning
  • Static method block : static {} Packaged code blocks
  • General attribute : Not static Properties defined
  • Common method block : {} Packaged code blocks
  • Constructors : Class names are the same way
  • Method : Common method

To verify the order of initialization , The best way to do this is to write code and practice

public class TheOrder {
        //  Static attribute 
        private static String staticField = getStaticField();
        //  Static method block 
        static {
            System.out.println(staticField);
            System.out.println(" Static method block initialization ");
        }
        //  General attribute 
        private String field = getField();
        //  Common method block 
        {
            System.out.println(field);
        }
        //  Constructors 
        public TheOrder() {
            System.out.println(" Constructor initialization ");
        }

        public static String getStaticField() {
            String statiFiled = "Static Field Initial";
            return statiFiled;
        }

        public static String getField() {
            String filed = "Field Initial";
            return filed;
        }
        //  The main function 
        public static void main(String[] argc) {
            new TheOrder();
        }
}

The final output is zero

Static Field Initial
 Static method block initialization 
Field Initial
 Constructor initialization 

So the initialization order is :

  1. Static property initialization
  2. Static method block initialization
  3. Normal property initialization
  4. Common method block initialization
  5. Constructor initialization

this and super

this and super All are Java Keywords in

this

this This keyword can only be used in the method body of a method . When an object is created ,JVM The object will be assigned a pointer to refer to itself , The name of this pointer is called this .

this The current object represents , Can be used to call methods 、 Properties and the object itself .

public class Test{
  private int number;
  private String username;
  private String password;
  private int x = 100;
  
  public Test(int n){
    number = n;// This can be written as this.number = n;
  }

  public Test(int i, String username, String password){
  // Member variable and parameter have the same name , Member variables are masked , use "this. Member variables " Access member variables in the way of .
    this.username = username;
    this.password = password;
  }

  // Default construction method without parameters 
  public Test(){
    this(0, " Unknown ", " empty ");// adopt this Call another constructor .  
  }

  public Test(String name){
    this(1, name, " empty ");
  /*
   *  adopt this Call another constructor .  Although the above two construction methods are compiled through . But it doesn't make any sense . In general, we will use it in constructors with many parameters this Call constructors with fewer arguments ( And it can only be placed in the first line of the method body ).
   *  The construction method in the example is equivalent to giving three parameters ( Two of these parameters have been set , This method passes in another parameter ). 
   */
  }

  public Test(int i, String username){
    this(i, username, null);// adopt this Call another constructor .  
  }

}

this Summary of usage

  1. adopt this Call another constructor in this class , Usage is this ( parameter list ), This can only be used in class constructors , And it can only be placed in the first sentence of the method body of the constructor of a class . You can't use it anywhere else .
  2. When a method parameter or a local variable in a method has the same name as a member variable , Member variables are masked , To access member variables, you need to use “this. Variable name ” To reference a variable . however , In the absence of the same name , You can use the name of the member variable directly , without this , It's also right to use it ( It looks more intuitive ).
  3. In the method , When you need to reference the current object of the class to which the method belongs , Direct use this.

super

  1. In the subclass constructor, the constructor of the parent class is called , use “super( parameter list )” Method call , Parameters are not necessary ( If the subclass constructor does not have a parameter , But the constructor of the parent class has this parameter , So in super() The corresponding position in the parameter list of , Pass in the parameter null ).
  2. If a subclass overrides a method of the parent class .( In other words, the child class and the parent class have the same method definition , But there are different approaches ), here , We can go through "super. Legal name of member " To call the method in the parent class .

Three characteristics of object-oriented

encapsulation

Packaged in Java Also known as access control rights in , In fact, the core of access control is : Only visible to the required classes .

Java There are four kinds of access rights for members in , Namely public、protected、default、private, Their visibility is as follows

Same class Same package Subclasses of different packages Non subclass of different packages
public
protected
Default (default)
private

Inherit

Inheritance is all OOP Language and Java An indispensable part of language .

Inheritance is Java A cornerstone of object-oriented programming technology , It's one of the three characteristics of facing an object , It is also an important means to realize software reuse , Inheritance can be understood as the process in which an object obtains properties from another object .

When we are ready to write a class , Find that a class already has the member variables and methods we need , If we want to reuse the member variables and methods of this class , That is to say, without declaring a member variable in the written class, it is equivalent to having this member variable , Without defining a method is equivalent to having this method , Then we can declare the class written as a subclass of this class, that is, inheritance .

Source class , Base class , Superclass perhaps Parent class It's all a concept

Export class , Inheritance class , Subclass It's the same concept

The two most commonly used keywords in inheritance are extends and implements .

The use of these two keywords determines whether an object and another object are IS-A ( It's a ) Relationship .

By using these two keywords , We can implement one object to get the properties of another .

all Java The classes of are all created by java.lang.Object Class , therefore Object Is the ancestor class of all classes , Besides Object Outside , All classes must have a parent class .

The grammar of inheritance

class Father{
    private int i;
    protected int j;
    
    public void func(){
        
    }
}

class Son extend Father{
    public int k;
    
    public void func(){}
}
Be careful : For example, the class declaration statement does not contain extends Clause , Then the class is java.lang In bag Object Subclasses of . That explains it java In fact, the code in has an inheritance relationship , It's just inheritance Object This java The most fundamental parent class in .

The characteristics of inheritance

  1. Child class has parent class not private Properties and methods of , The parent method and member variable inherited by subclass can be used by instance method of subclass as its own method and member variable .
  2. Subclasses can have their own properties and methods , That is, the subclass can extend the parent class on the basis of the parent class .
  3. Subclass can implement the method of parent class in its own way .( Rewrite or override )

polymorphic

Polymorphism is the ability of one behavior to have many different forms or forms . Polymorphism is the same interface , Use different instances to perform different operations .

Polymorphism is another important feature of object-oriented programming , It means that the properties and methods defined in the parent class are inherited by the child class , Can have different data types or behave differently , This makes the same attribute or method have different meanings in the parent class and its subclasses . For object-oriented , Polymorphism can be divided into compile time polymorphism and run time polymorphism . The compile time polymorphism is static , Mainly refers to the method overload , It distinguishes different methods according to different parameter lists . After compiling, it will become two different methods , There's no polymorphism at runtime . And runtime polymorphism is dynamic , It is implemented through dynamic binding , That's what we call polymorphism .
e.g. Color printers and black-and-white printers are printers , But they print things in different colors . This is polymorphism

The conditions for polymorphic implementation

  1. Inherit : There must be subclass and superclass with inheritance relationship in polymorphism .
  2. rewrite : Subclass redefining some methods in the parent class , When these methods are called, the subclass's methods are called , If there is no override, it will be called in the parent class . When subclass objects call overridden methods , It is the method of the subclass that is called , Not the overridden method in the parent class . To call the overridden method in the parent class , Keywords must be used super.
  3. Upward transformation : In polymorphism, you need to assign a reference of a subclass to a parent object , Only in this way can the reference call the method of the parent class , Can call the method of subclass again .
public class Person {
    
    public void drink(){
        System.out.println(" Drink coffee ");
    }
    
    public void eat(){
        System.out.println(" Have something to eat ");
    }
}

public class Man extends Person {
    public void drink(){
        System.out.println(" Drink ice American ");
    }
}

public class Test {
    public static void main(String[] args) {
        Person p = new Man();
        p.drink();
        p.eat();
    }
}
 Output :
 Drink ice American 
 Have something to eat 

Advantages of polymorphism

  1. Eliminate coupling between types
  2. Replaceability
  3. Extensibility
  4. Interface
  5. flexibility
  6. Simplicity

Interfaces and abstract classes

Interface

Interface ( english :Interface), stay Java Programming language is an abstract type , Is a collection of abstract methods , The interface usually uses interface To declare . A class inherits an interface by way of , So as to inherit the abstract methods of the interface .

Interfaces are not classes , Interfaces are written in a similar way to classes , But they belong to different concepts . Class describes the properties and methods of an object . The interface contains the methods that the class will implement . Unless the class that implements the interface is an abstract class , Otherwise, the class will define all methods in the interface .

Interface cannot be instantiated , But it can be realized . A class that implements an interface , All methods described in the interface must be implemented , Otherwise, it must be declared as an abstract class .

Interfaces and classes are similar :

  • An interface can have multiple methods .
  • Interface files are stored in .java In the closing document , The file name uses the interface name .
  • The bytecode file of the interface is stored in .class In the closing document .
  • The corresponding bytecode file of the interface must be in the directory structure matching the package name .

The difference between interface and class :

  • Interfaces cannot be used to instantiate objects .
  • Interface has no constructor .
  • All methods in an interface must be abstract methods .
  • Interface cannot contain member variables , except static and final Variable .
  • Interface is not inherited by class , But to be implemented by class .
  • Interface supports multiple inheritance .

Interface declaration

[ visibility ] interface  The name of the interface  [extends  Other class names ]{
    //  Declare variables 
    //  Abstract method 
}

Example :

public interface TestInterface{
    public void eat();
    public void drink();
}

Interface implementation

Class implements the interface , Class to implement all the methods in the interface . otherwise , Class must be declared as an abstract class .

Example :

public class Test implements TestInterface{
    public void eat(){
        System.out.println(" Eat something ");
    }
    
    public void drink(){
        System.out,println(" Drink lots of water ");
    }
    
    public static void main(String args[]){
        Test t = new Test();
        t.eat();
        t.drink();
    }
}

When implementing the interface , it is to be noted that :

  • A class can implement multiple interfaces at the same time .
  • A class can only inherit one class , But it can implement multiple interfaces .
  • One interface can inherit another , This is similar to inheritance between classes .

abstract class

A class does not contain enough information to describe a specific object , Such a class is an abstract class .

An abstract class can't instantiate an object , Other functions of the class still exist , Member variables 、 Member methods and construction methods are accessed in the same way as ordinary classes .

Because abstract classes cannot instantiate objects , So the abstract class has to be inherited , To be used . That's why , Usually at the design stage, we decide whether to design abstract classes or not .

The parent class contains common methods for the collection of subclasses , But because the parent class itself is abstract , So you can't use these methods .

stay Java of use abstract class To define abstract classes .

public interface Test {

    void ColorTest();

}

abstract class WhiteDog implements Dog{

    public void ColorTest(){
        System.out.println("Color is white");
    }

    abstract void MMiniTest();
}

In an abstract class , Has the following characteristics

  • If there are abstract methods in a class , So this class must be an abstract class , in other words , Use keywords abstract The modified method must be abstract , A class with an abstract method must be an abstract class . In the implementation class method, only the concrete implementation of the method .
  • Abstract methods are not necessarily the only abstract methods in an abstract class , Abstract classes can also have concrete methods , You can choose whether to implement these methods on your own .
  • Constraints in abstract classes are not as strict as interfaces , You can define... In abstract classes Construction method 、 Abstract method 、 General attribute 、 Method 、 Static properties and static methods
  • Abstract classes, like interfaces, cannot be instantiated , Instantiation can only instantiate Specific classes

版权声明
本文为[Ordinary netizens]所创,转载请带上原文链接,感谢

Scroll to Top