Java Code Audit Java Foundation

Posted by quecoder on Fri, 07 Jan 2022 18:39:42 +0100

0. Preface

Two suggestions:
  ~go B Station Find Java Learn the course once
  ~I understand that I must follow the instructions and do more than once

This article summarizes more categories, not suitable for beginners, beginners suggest to go B Stop learning.

1. Overview and Basic Grammar

Introduction to 1.1 java language

Codes are usually organized as classes, encapsulating data in the mind of objects.
1.1.1 Object Oriented
Two basic concepts:Classes, Objects

Four characteristics:Encapsulation, Inheritance, Polymorphism, Abstraction

Purpose of encapsulation:Safety, simplification

java The process in which a program runs:
	(1)Compile:java file ===Compile as==> class file
	(2)Function:Run by our system class 

	polymorphic: References to parent classes point to objects of subclasses, and references to interfaces point to objects of implementing classes 
	Interface: Is a specification and a standard abstraction:Classes are abstracts,
	object: Objects are concrete, instantiated from class templates 	Keyword, new
1.1.2 Robustness
Absorbed C/C++Language has the advantage of removing the parts that affect the robustness of the program.	as:Application and Release of Pointer and Memory Java Will help with this
1.1.3 Cross-platform
Cross-platform: adopt Java Language-written applications can run on different system platforms.

principle: 	Run as long as needed java On the operating system of the application,
		Install one first Java virtual machine (JVM Java Virtual Machine) That's it.
		from JVM To be responsible Java The program runs in this system.

The result is a write, export run

1.2 Core Mechanism - Java Virtual Machine

JVM Is a virtual computer that has a set of instructions and uses different storage areas.

Responsible for executing instructions, managing data, memory, registers.

1.3 Core mechanism - garbage collection

  • 1. Garbage collection: Recycle memory space that is no longer used.

  • 2. In languages such as C/C++, the programmer is responsible for Reclaiming unused memory.

  • 3. Java does not require programmers to reclaim unwanted memory:

    It provides a system-level thread to track the allocation of storage space.

    And when the JVM is idle, check for and release those freeable storage spaces.

    Garbage collection occurs automatically when a Java program is running, and programmers cannot precisely control and intervene.


Comments are human-looking and the machine automatically ignores the relevant code when it parses them.

Comments are for the extensibility and maintainability and readability of the provider.
1.4.1 Single line comment
format: //Note Text
1.4.2 Multiline Comments
format: /*Note Text*/ 

For single- and multiple-line comments, the text being commented on will not be JVM(java virtual machine)Explain execution. 

Multi-line comment nesting is not allowed inside a multi-line comment.
1.4.3 Document Comments
Its meaning is to explain the author of the document, the time it was created, and the functions it accomplished. Same comment character as multiline comment

1.5 Keyword

Everything java A character defined by the language itself, called a keyword
1,Definition and characteristics of keywords 
	Definition:cover Java Language gives special meaning to strings used for specific purposes(Word) 
	Characteristic:All letters in keywords are lowercase
supplement:java Language is a strongly typed programming language that strictly distinguishes the types of variables.

For example:

byte short

double char

true flase

case default

break continue

And so on, not in the narrative.

1.6 Identifier


(1)Java The sequence of characters used to name features such as variables, methods, and classes is called an identifier

(2)Anywhere you can name yourself is called an identifier.

2. Define legal identifier rules:

(1)Uppercase and lowercase letters, numbers:0-9 ,_or $ Form. 

(2)Numbers cannot start.

(3)Keyword and reserved words are not allowed. 

(4)Java Medium is case sensitive and has unlimited length. 

(5)An identifier cannot contain spaces.

Note: When naming, in order to improve readability, try to be as meaningful as possible,'Know what you see'.

1.7 Naming Specification

1. Naming Specifications

1,Package Name:All letters are lowercase when multiple words are formed:xxxyyyzzz 

2,Constant name:All letters are capitalized. Underline each word when multiple words:XXX_YYY_ZZZ 

3,Class name, interface name:Capitalize the first letter of all words when they are composed of multiple words(Camel):XxxYyyZzz 

4,Variable name, function name:The first letter of a word is lowercase, followed by the first letter of each word in uppercase(Hump):xxYyyZz 

2. Naming Rules:
Convention, wisdom

1.8 Variables

Definition of 1.8.1 Variable

1. Concepts of variables:

(1)A storage area in memory 

(2)This area has its own name(Variable Name)And types(data type) 

(3)Java Each variable in must be declared first(Define data types),Post-use 

(4)The data for this area can vary over the same type of range 

2. Define the format of variables: data type variable name = initialization value

3. Variables access this area by using variable names

4. Java is a strongly typed language. Each variable must declare its type before it can be used.

5. Use variables Note: Scope of variables: Valid between pairs of {}

Classification of 1.8.2 Variables
For each type of data, a specific data type is defined, and different sizes of memory space are allocated in memory. By Data Type

For each type of data, a specific data type is defined, and different sizes of memory space are allocated in memory.

1. There are four types of integers.

Namely byte,short,int,long
  • java integer types have a fixed range of tables and field lengths and are not affected by specific OS to ensure portability of java programs.
  • Java integer constants default to int, long constants are declared with'l'or'L'

    2. Floating point (decimal) type
2 Species, respectively float,double
Similar to integer types, Java Floating point types also have a fixed number of table ranges and field lengths that are not specific OS Impact. 

Java Floating-point constant defaults to double Type, declaration float Type constant, followed by 'f' or 'F'.  

Floating-point constants have two representations:

Decimal Number Form:as:5.12 512.0f  .512 (Must have decimal point)

Scientific Counting Form:as:5.12e2 512E2  100E-2

3. Character type

Java Strings can only be enclosed in single quotation marks, not double quotation marks


Strings can only be enclosed in double quotes, not single quotes.

4. Boolean Types

boolean Type data only allows values true and false,

Can not be replaced by 0 or non-0 integers true and false,

This point and C Language is different Declared Location Division
Member variables(Belonging to class):Variables defined externally by methods and internally by classes

local variable(Belonging to method):Variables defined within a method or statement block

Note: There can be no variable declaration outside the class (outside the curly brackets corresponding to the class) by data type
By data type:

1. Basic data type variables

2. Reference data type variables (all but eight basic data types are reference types)

The basic types include:
byte,	short,	int,	long,	

char,	float,	double,	Boolean,

No String

1.8.3 Data Type Conversion Basic Data Type Conversion
  Automatic Type Conversion:Small types are automatically converted to large data types. Data types are sorted by capacity size:

When there are multiple types of data mixing operations, the system first automatically converts all the data to the data type with the largest capacity, and then calculates it.

byte,short,char There is no conversion between them, they all convert to int Type. 

When concatenating values of any basic type with string values(+),Values of the base type are automatically converted to string types. Cast
boolean Types cannot be converted to other data types.

1.9 Operator

1.9.1 Arithmetic Operator

One thing to note:

The result of dividing is to figure out the decimal part directly, leaving only the integer part.

If you want the result to be rounded, you need to call the corresponding API(Function)

1.9.2 Assignment Operator
Symbol: =

Extended assignment operator: +=, -=, *=, /=, %=
1.9.3 Comparison Operator

Note 1:The result of the comparison operator is boolean Type, that is, either true,Either false.  

Note 2:Comparison Operator=="Can't be miswritten as "=" . 
About the difference between'=='and equals:
"==" Simply compare the reference addresses, not the contents.

	For basic data type variables, there is no reference address and they are all on the stack.
	So "=="For basic data types, the comparison is value (content).
	For reference type variables, such as String For variables of type, address is the comparison.

Summary of "==": 
	Basic type: Compare values are the same or not;
	Reference type: Compare whether the references are the same or not;

equals Essentially, " == ",however String,Integer Wait rewrite equals,

Turn it into a value comparison, so it's usually called in the program equals Are the values of comparison equal.

1.9.4 Logical Operators

(1) Logical operators are used to connect Boolean expressions. They cannot be written as 3<x<6 in Java. They should be written as x>3&x<6.

  • In single-time, operations are performed on the left, true or false, and on the right.
  • If the left side is true, the right side participates in the operation, and if the left side is false, the right side does not participate in the operation.
  • The same difference as'||', when double or, the left side is true and the right side does not participate in the operation.
  • The difference between XOR (^) and OR (|) is that for ^, when both left and right are true, the result is false.
1.9.5-bit operator

A bitwise operation is a direct operation on binary

1.9.6 Ternary Operator

(Conditional expression)?Expression 1:Expression 2; 

If the condition is true,The result of the operation is expression 1; 

If the condition is false,The result of the operation is expression 2;

1.10 Branch Structure

1.10.1 if else

1.10.2 switch

Assuming that the statement in case does not have a "break", the statement in default will also be executed.

public class test {
    public static void main(String[] args) {
        int i = 1;
        switch (i) {
            case 0:
            case 1:
                //Break; // Default is the last possibility, so you don't need to add "break".

Output results:

The default clause is optional, that is, you may not have it, but it is recommended to add it for the robustness of the program.

1.11 Cycle Structure

1.11.1 Loop Statement

Loop statement classification:

for loop(Common) 

while loop 

do/while loop
1.11.2 for statement
Grammar Format

	for (Initialization expression; Boolean Test Expression; Change expression){
		Statement or statement block;

Examples of applications
	public class ForLoop {
        public static void main(String args[]){
            int result = 0;
            for(int i=1; i<=100; i++) {
				result += i;//Circulatory body 
            System.out.println("result=" + result);
1.11.3 while statement
public class Test {
  public static void main(String args[]) {
	int a = 1;//Loop Initialization
	while (a < 10) {//Boolean expression, also called conditional judgment
		System.out.println(a); //Circulatory body
		a++;//The end condition of a loop, also known as an iteration, is an endless loop if there is no such part of it}		
	System.out.println("while End of cycle");
} }
1.11.4 do while statement


While loops are judgement followed by execution, while do while loops are execution followed by judgement.

That is, do while loops, the body of a loop will execute at least once, regardless of the Boolean expression.

1.12 Process Control Statements

1.12.1 break
break Statement requirements: 

break Statement is used to terminate execution of a statement block


break When a statement appears in a multi-level nested statement block, the label can indicate which level of statement block to terminate. 

  label1: { ......
  label2: { ......
  label3: { ......
                break label2;
          ...... }
  } }
1.12.2 continue
continue Statement is used to skip one execution of a loop statement block

continue When a statement appears in a multi-level nested loop body, you can indicate by label which level of loop you want to skip


break Can only be used for switch Statement and loop statement.

continue Can only be used in loop statements. 

The label statement must be immediately at the beginning of the loop. The label statement cannot be used before an uncycled statement. 

break and continue There can be no other statements since the program will never execute break and continue The following statement.

1.13 Array

Arrays are a combination of multiple data of the same type to achieve uniform management of these data 

Arrays are reference types, and array data is objects(Object),Each element in the array corresponds to a member variable of the object 

Elements in an array can be of any data type, including basic and reference types 

But only if it is stated that it is the same type of data you store.
1.13.1 One-dimensional array One-dimensional array declaration
Declarations of one-dimensional arrays: type var[] or type[] var; 
	for example:
		int a[];
		int[] a1;
		double b[];
		Mydate []c; //object array

Java You cannot specify the length of an array when it is declared in a language(Number of elements in the array), for example: int a[5]; //illegal Array Initialization
An array is a reference type whose elements correspond to the member variables of a class, so once space is allocated to the array,

Each of these elements is also implicitly initialized in the same way as the member variables. for example:

	public class Test {
	public static void main(String argv[]){
		int a[]= new int[5]; 
		System.out.println(a[3]); //The default value for a[3] is 0}
	} Create an array of objects

1. Array initialization

dynamic initialization:Array definitions are separated from allocating space and assigning values to array elements.

1.13.2 Multidimensional Array
Java Medium multidimensional arrays are treated as arrays

Java Declarations and initializations of mid-dimensional arrays should be in order from high to low dimensions

java Medium multidimensional arrays do not have to be regular matrices Multidimensional Array Initialization
  • initiate static

  • dynamic initialization

2. Advanced Object-Oriented and Class Properties

2.1 Classes and Objects

2.1.1 Object Oriented Concepts
1. Process Oriented

	Define the size, position, color, background and other properties of the window in a structure.
	A function that operates on a window has nothing to do with the definition of the window itself, such as HideWindow,MoveWindow,
	MinimizeWindow,These functions need to accept a window parameter representing the operation to be performed.
	Is the relationship between a predicate and an object. The center is in the process of implementing a problem or completed function

2. Object-oriented
	When defining a window, in addition to specifying the properties specified in the face-to-face process, such as size, position, color, background, etc.
	Also specify the actions that the window may have, such as hiding, moving, minimizing, and so on. When these functions are called,
	They are used in the grammatical format in which a window is hidden and a window is moved. This is the relationship between the subject and the predicate.
	Focus on the object, just know what object has what method to use and call it

3. Three Object-Oriented Features 
	encapsulation (Encapsulation) inherit (Inheritance) polymorphic (Polymorphism)
2.1.2 Object Oriented Thought
The idea of object-oriented programming tries to make the description of things in computer language as consistent as possible with what they are in the real world. 
class(class)And objects(object)Is the core concept of the object-oriented approach.

A class is a description of a class of things, an abstract, conceptual definition;The object is each individual of this kind of thing that actually exists.
So also called instance(instance).  

Class is a template and object is a specific instance of the template
2.1.3 Classes and Objects

Definition of class 2.1.4
  • Examples of declaring attributes
public class Person{
	private int age;		 //Declare private Variables 
	age public String name = "Lila"; 		//Declare the public variable name
  • Declare Method
public class Person{
	private int age;
	public int getAge() { return age; } 		//Declare Method
	getAge public void setAge(int i) { 		//Declare method setAge
		age = i; 		//Assign the value of parameter i to the member variable age of the class 
	//The method is sometimes called a member function (function)

Multiple classes can exist in a file, but only one class can be decorated with public

Creation and Use of 2.1.5 Objects
Use new +Constructor creates a new object;

Use Object Name.Access object members by way of object members(Include properties and methods)

Class access mechanism:

Access mechanism in a class:Methods in a class have direct access to member variables in the class.(There is one exception)

Access mechanism in different classes:Create an object to access the class, then use the object to access the members defined in the class.
Use of 2.1.6 Objects

First create an object:

class Person
    int age;
    void shout()
        System.out.println("oh,my god! I am " + age);
Person p1 = new Person();
After creating a new object,So we can use the Object Name.Format of object member to access object properties
class TestPerson
	public static void main(String[] args) {
	 	Person p1 = new Person();
		Person p2 =new Person();
		p1.age = -30;
} }
2.1.7 Anonymous Objects
Instead of defining a handle to an object, we can call its methods directly. Such objects are called anonymous objects.

 as:new Person().shout();

Anonymous objects can be used if there is only one method call to an object. 

We often pass anonymous objects as arguments to a function call.

2.2 Encapsulation and Hiding of Information

2.2.1 Necessity
User-defined attributes within a class(Member variable of object)Direct operations can result in errors, confusion, or security problems with the data.

You should add legs Property is protected against misuse. Ways to protect:information hiding 

Such as a problem:xb.legs=-1000;
2.2.2 private keywords
Java By declaring data private in(private),Re-provide publicly available(public)Method:
		getXXX and setXXX Implement operations on this property,

To achieve the following objectives:
		Hide implementation details for a class;

		Users can only access data in a pre-defined way, which allows them to easily incorporate control logic to limit improper manipulation of attributes;
		Easy to modify to enhance code maintainability;
public class Animal{
	private int legs; 		//Defining the property legs as private can only be accessed internally by the Animal class 
	public void setLegs(int i){ //Define the methods eat() and move() here
	        if (i != 0 && i != 2 && i != 4){
	             System.out.println("Wrong number of legs!");
	public int getLegs(){
        return legs;

public class Zoo{
    public static void main(String args[]){
    	Animal xb= new Animal();
		xb.setLegs(4);    	//xb.setLegs(-1000);
		xb.legs=-1000; 		//illegal 
} }

2.3 Construction Method (Constructor)

Definition and function of 2.3.1 constructor
  • Characteristics of construction methods

      It has the same name as the class;
      It has no return value; 

    Be careful:

      The concept of no return value in a construction method is different from " void"'s'is added when defining the construction method. void",
      As a result, this method is no longer automatically adjusted
  • The role of construction methods

      When an instance object of a class is first generated, its construction method is called automatically.
      We can add code to this method to complete the initialization.
      It's like we stipulate that every "person" must take a bath at birth, so we can add the program code to complete the "bath" in the construction method of "person".
      So every person will automatically take a bath at birth.
      The program doesn't have to tell everyone to "bathe" one by one at birth.
2.3.2 Form of Form
function:When an instance of a class is created, a set of instructions initializing the instance.

Give an example:

public class Animal {
	private int legs;
	public Animal() {legs = 4; } //constructor 
	public void setLegs(int i) 
		{ legs = i; } 
	public int getLegs(){return legs;}
Establish Animal Instances of classes:Animal a=new Animal(); //Initialize legs to 4 by calling the constructor

Be careful:

The name of the constructor must be the same as the class name. Modifier:public,private,protected

Constructor is not a general method, no return value(even void Nor can I write)

2.3.3 Default Construction Method
Java Each class has at least one construction method in the language; 

If the class definer does not explicitly define any construction methods, a default construction method is automatically provided:
	(1)Default construction method has no parameters
	(2)Default construction method has no method body
	(3)Default construction method:Animal(){}

therefore:Available without writing a construction method new Xxx()Create an instance of the class.

In Java classes, once the class's definitor explicitly defines one or more construction methods, the system will no longer provide default construction methods.

The primary role of constructors:Initializes the properties of the object with constructor parameters.

Overload of 2.5 Method

  • Occurs in the same class
  • Method names are identical
  • Has nothing to do with the return type
  • Parameter lists are different (number, type, order of parameters)
The overload of a function is to allow more than one function of the same name to exist in the same class at the same time, provided they have different numbers or types of parameters. 

For example:

Multiple methods with the same name can be defined in the same class - method name overload(overload)

The parameter list of overloaded methods must be different

Return value types of overloaded methods can be the same or different

The method is called differently based on its parameter type.

2.5.1 Construction Method Overload
public class Person {
    private String name;
    private int age;
    private Date birthDate;
    public Person(String name, int age, Date d) { = name;
    this.age = age;
    this.birthDate = d;
     public Person(String name, int age) {
    this(name, age, null);    //; this.age=age;
    public Person(String name, Date d) {
    this(name, 30, d);     //;
     public Person(String name) {
     this(name, 30);       //; this.age=30;
} }

2.6 this keyword

Inside each member method, there is one this Reference variable to the object calling this method,

2.7 import statement and package statement

thought:Large number of calls to three parties API,You cannot write on your own.

package Statement as Java The first statement of the source file specifies the package in which the classes defined in the file are located.
		(If the statement is defaulted, it is specified as an unnamed package). 	

For example:

2.7.2 import statement
Defined in different packages for use Java Class, required import Statement to introduce the required class.

Import Statement tells the compiler where to look for classes.

For example:

Inheritance of class 2.8

Parent Class:To describe and process personal information, define classes Person

Subclass:To describe and process student information, define classes Student

Java Single inheritance only, multiple inheritance not allowed 

A subclass can have only one parent, and a parent can derive multiple subclasses

Rules on inheritance:

 Subclass cannot inherit private from parent(private)Member variables and methods.

Simplify the definition of the Student class by inheriting:

2.9 Access Control

You can Java Attributes and methods defined in classes for access control----Specify different levels of protection:

		public,protected, default,private

Rewrite of 2.10 Method

Occurs between parent and child classes with the same method(Return value type, parameter list, method name),Only if the method body is different
  • In subclasses, methods inherited from the parent can be modified as needed - override methods (reset, override of methods), and subclass methods override parent methods when a program executes.
  • Override methods must have the same method name, parameter list, and return value type as overridden methods.
  • Override methods cannot use stricter access rights than overridden methods.

2.11 super keyword

Keyword super Represents the parent object, in Java Use in Class super To refer to the parent's components
  • super can be used to access properties defined in the parent class

  • super can be used to call member methods defined in the parent class

  • Sup can be used to invoke a parent class's construction method in a subclass construction method

  • super tracing is not limited to direct parent classes

  • Construction method cannot inherit

      Subclasses inherit all member variables and methods of the parent class, but do not inherit construction methods of the parent class 
      In one Java There are two ways to get construction methods in a class
      		~Use the system default parameterless construction method
      	 	~Explicitly define one or more construction methods
      However, once the construction method is explicitly defined, the system no longer provides a default construction method
  • Call parent class construction method

      Used in the construction of subclasses super(parameter list)Statement calls the construction method of the parent class,
      If the parent class construction method is not explicitly called in the child class construction method, it is not used this Keyword calls another overloaded constructor,
      The system calls parent class parameterless constructors by default, and calls parent class constructors are not shown in child class constructors.
      Compilation error if there is no parameterless construction method in the parent class

2.12 Polymorphism

  • Subclass objects can be used instead of parent objects in Java
  • A variable can have only one deterministic data type
  • A variable of reference type may point to (reference) many different types of objects
Person p = new Student();

Object o = new Person();//Variable o of type Object, pointing to an object of type Person 

o = new Student(); //Variable o of type Object, pointing to an object of type Student
  • Variables of the parent type can point to objects of the child class (that is, Person e = new Student());

If a variable of reference type is declared as the type of the parent class but actually refers to a subclass object,

Then the variable no longer has access to the properties and methods added in the subclass

Student m = new Student(); = "pku"; //Legal, the Student class has the school member variable Person e = new Student(); = "pku"; //Illegal, Person class has no school member variable

Property is determined at compile time, compile time e is Person type, no school member variable, compile error.

1,Normal method calls

	Person e = new Person();
	Student e = new Student();

2,Virtual Method Call(Polymorphic case)
	Person e = new Student();
	e.getInfo(); //Call the getInfo() method of the Student class

Compile-time e by Person Type, and method calls are determined at runtime.

So what's called is Student Class getInfo()Method(Dynamic Binding)

Compile to the left, execute to the right

2.13 instance operator

x instanceof A:test x Is it a class A Object that returns a value of boolean Type.

Requirement x Classes and classes to which they belong A Must be a relationship between child and parent, otherwise compilation error. 

If x Belonging to class A Subclasses B,x instanceof A Value is also true. 

2.14 Object Type Conversion (Casting)

2.14.1 Basic Data Types
  • Small data types can be automatically converted to large data types, such as long g=20; double d=12.0f
  • Large data types can be cast into small data types. Such as floate f=(float)12.0; int a=(int)1200L
2.14.2 Mandatory type conversion of Java objects is called styling
  • Type conversion from subclass to parent class can occur automatically
  • Type conversion from parent to child must be done through styling (forced type conversion)
  • Conversion between reference types without inheritance relationship is illegal
  • You can use the instanceof operator to test the type of an object before styling

2.15 Object Class

Object Classes are all Java Root parent of class

If not used in class declaration extends If the keyword indicates its parent class, the default parent is Object class

2.16 equals method and==

Reference top: 1.9.3 Comparison operator

2.17 toString

  • The toString() method is defined in the Object class and its return value is of type String, returning the class name and its reference address.
  • The toString() method is automatically called when a String is connected to other types of data

  • When the basic type data is converted to String type, the toString() method int a=10 of the corresponding encapsulated class is called.


2.18 Encapsulation Class

For eight basic definitions of corresponding reference types - encapsulation classes

2.19 static keyword

  • When declaring variables, methods, and internal classes in Java classes, you can use the keyword static as a modifier.
  • Variables or methods marked with static are shared by the entire class (all instances), and if access control permissions permit, the class name can be added with a'. 'instead of creating the class object. Called.
  • Static members are also called class members or static members, such as class variables, class methods, static methods, and so on.
    The design ideas of class attributes and class methods:
  • Class attributes are variables that are shared among objects of this class. When designing classes, analyze which class properties do not change with the object and set them as class properties. The corresponding method is set to the class method.
  • If a method is unrelated to the caller, such a method is usually declared as a class method, which simplifies method invocation by invoking the class method without creating an object

2.20 final keyword

  • When declaring classes, properties, and methods in Java, you can decorate them with the keyword final.

  • A final-marked variable (a member variable or a local variable) becomes a constant and can only be assigned once.

  • The final tag class cannot be inherited. Improve security and readability of programs.

  • The final tag's method cannot be overridden by a subclass. Increase security.

  • A final tag's member variable must be explicitly assigned at the same time it is declared or in each construction method before it can be used.

      final PI=3.14;

For example:

2.20 Abstract Classes

  • As new subclasses in the inheritance hierarchy are defined, classes become more specific, while parent classes become more general and generic. Classes should be designed to ensure that features are shared between parent and child classes. Sometimes a parent class is designed so abstract that it has no concrete instance. Such a class is called an abstract class.
  • When a class is decorated with the abstract keyword, it is called an abstract class. When a method is decorated with abstract, it is called an abstract method
  • Abstract method: There is only a declaration of the method, no implementation of the method. End with a semicolon.
  • abstract int abstractMethod1( int a );
  • Classes containing abstract methods must be declared abstract.
  • Abstract classes cannot be instantiated. Abstract classes are used to be inherited, and subclasses of abstract classes must override the abstract method of the parent class and provide the body of the method
  • Private methods, construction methods, static methods cannot be decorated with abstract.

2.21 interface

1. Definition of interface
Sometimes a subclass must be derived from several classes, inheriting all their properties and methods.
However, Java Multiple inheritance is not supported.	With an interface, you can get the effect of multiple inheritance.

Interface(interface)Is a collection of abstract methods and definitions of constant values. Interfaces are essentially a special Abstract class.
This abstract class contains only the definitions of constants and methods, not the implementation of variables and methods.
2. Examples of interface definitions

3. Interface features:
  • Define with interface.
  • All member variables in an interface are decorated by public static final by default.
  • All methods in the interface are decorated by public abstract by default. Interface has no construction method.
  • Specific implementations of all methods in an interface must be provided in the class that implements the interface.
  • Multiple unrelated classes implement the same interface
  • A class can implement multiple unrelated interfaces
  • Similar to inheritance, there are polymorphisms between interfaces and implementation classes
  • An interface can also inherit another interface, using the extends keyword.
4. Interface requirements:
  • Specific implementations of all methods in an interface must be provided in the class that implements the interface.
  • Multiple unrelated classes implement the same interface
  • A class can implement multiple unrelated interfaces
  • Similar to inheritance, there are polymorphisms between interfaces and implementation classes


  • If the class that implements the interface does not implement all the methods in the interface, it must be defined as an abstract class.
  • An interface can also inherit another interface, using the extends keyword.

Topics: Java bash