Notes on Java learning

Notes on Java introduction 2 - Hao bin abstract class Abstract method abstract class Final keyword Final decorates t...
Abstract method
abstract class
Final decorates the entire class
Some properties in the Final modifier class
Definition of interface
Format of interface
Syntax knowledge of interface
Function of interface
The difference between interface and abstract class
Use of package
Why exceptions are needed
Exception handling mechanism
Classification of exceptions
Exception handling steps:
Abnormal advantages and disadvantages

Notes on Java introduction 2 - Hao bin

abstract class
  1. The origin of abstract classes
    Abstract classes are used to better classify classes, just as human beings not only name specific plants, but also invent the abstract word "plant" to classify all specific plants
  2. Java is used to simulate the real world, so there are abstract classes
  3. Abstract class is usually used as the top-level parent class of a class family. The bottom-level class represents the concrete things in reality, and the top-level class represents the commonness of all things in the class family.

Abstract method

  • When defining a Java method, you can only give the method header, but not the internal implementation code of the method. Such a method is called abstract method
  • Methods without method bodies must be modified to abstract methods with key Abstract
  • All classes with abstract methods must be declared as abstract classes

abstract class

  • When an abstract keyword is used to modify a class, it is called an abstract class
  • The class containing the abstract method must be declared as an abstract class
  • But an abstract class can contain no abstract methods, although it is rare
  • Abstract classes do not have abstract methods
  • An abstract class must be an abstract method
// Classes with abstract methods must be abstract classes abstract class A { public void f(); //The method without method body is called abstract method. Abstract method requires semicolon at the end and abstract at the front } //Abstract classes do not have abstract methods abstract class B { public void g(){} }
abstract class A //If the f method has no method body, you must add abstract before class if the f method has a method body, //Class can be preceded by or without abstract, because "an abstract class can not contain any abstract methods, although it is relatively rare" { abstract void f(); //If f method has no method body, F method must be declared as abstract method, that is, it must be preceded by abstract } //class B extends A{} //error //abstract class B extends A{} // ok class B extends A // ok { public void f() { System.out.printf("BBBB\n"); } } class TestAbsPoly_1 { public static void main(String[] args) { //A AA = new a(); / / the error abstract class cannot be instantiated B bb = new B(); //OK bb.f(); // OK A aa; // OK defines a reference to an abstract class, aa = bb; //Assign the address of the subclass object to the reference of the abstract class aa.f(); //The method of accessing a subclass with the reference of an abstract class is called polymorphism } }
  • Abstract classes do not have abstract methods
  • An abstract class must be an abstract method
  • The abstract class object cannot be new, but the reference of an abstract class can be defined
  • We can assign the address of a subclass object to the reference of the abstract class, and then call the method inherited from the parent class by the reference of the abstract class, that is, the abstract class can also realize polymorphism
    Suppose a is an abstract class, B is a subclass of a and implements all the abstract methods of A
    A aa = new A();//error A aa = new B(); // OK
Final keyword
  • final can modify:
    1. Entire class
    2. Several properties in a class
    3. Some methods in class

Final decorates the entire class

  • Indicates that the class cannot be inherited
  • If you think a class is perfect and you don't need to define subclasses to inherit it, you can use it
  • Format:
    • public final class A {......}
    • public and final can be interchanged
//The final modifier class indicates that the class cannot be inherited //Properties decorated by final type must be initialized at the same time as they are defined //If a final type decorated property is not initialized at the same time as it is defined, it must be initialized in all constructors in the class //However, there can only be one of these two initializations, otherwise an error will be reported at compile time! Because final means constant, the constant cannot be initialized twice class A //If you add final before class, the program will report an error { final int a = 10;//Variables defined by final must be initialized at the same time //If only uninitialization is defined here, we must complete the initialization of final variable in all constructors //But you can only choose one of the two ways public A() { //a = 20; / / as long as a is initialized, this statement must be commented out. Otherwise, an error will be reported at compile time! } } class B extends A { } public class TestFinal { public static void main(String[] args) {} }

Some properties in the Final modifier class

  • Several properties in the Final modifier class indicate that the property must be assigned a value and can only be assigned a value once (note that the default value is not the real assignment)
  • There are two initialization methods: (only one can be selected)
    • Initialize while defining member variables
    • Initialize in all constructors in the class
  • Note: the value of member variable modified by final cannot be modified inside all ordinary methods of a class
//Indicates that the method can be inherited by subclass, but cannot be overridden by subclass class A { public void f() //If final is added before public, an error will be reported at compile time { System.out.println("AAAA\n"); } } class B extends A { public void f() //Override the f method of the parent class { System.out.println("BBBB\n"); } } public class TestFinal_1 { public static void main(String[] args) {} }
interface (interface)

Definition of interface

An interface is a collection of abstract methods and constant values. In essence, interface is a special abstract class

Format of interface

[public] interface interfaceName [extends SuperInterfaceList] { ...... // Constant definition and method definition }
interface It { int i = 20; public void f(); } abstract class B { public void f(){} } class A { public static void main(String[] args){} }

Syntax knowledge of interface

  1. The attributes defined in the interface must be public static final, and the methods defined in the interface must be public abstract, so these modifiers can be omitted in part or in whole
  2. The value of a property defined in an interface cannot be changed in an implementation class
  3. A class can only implement an interface, not inherit an interface
  4. A class can implement multiple interfaces, but a class cannot inherit multiple classes
  5. But an interface can inherit an interface
  6. The interface can not only inherit the interface, but also inherit multiple interfaces, that is, the interface allows multiple inheritance
  7. If a class implements only part of an interface's methods, the class must be declared as an abstract class
  8. A class can implement one or more interfaces while inheriting a parent class, but the extends keyword must precede implements
  9. It is not allowed to create new interface objects, but it is possible to define a variable of interface reference type and point it to the object implementing the interface to achieve polymorphism (the same as abstract class)
//Constructors cannot be defined in an interface interface It1 { public static final i = 20; // The attribute defined in the interface must be public static final public abstract void f(); //The methods defined in the interface must be public abstract, } interface It2 { int i = 20; // Therefore, these modifiers can be partially or completely omitted and cannot be changed to int i; void f(); } interface It3 extends It1, It2 //Interface can inherit interface, and can inherit multiple interfaces, that is, interface allows multiple inheritance { } class A implements It2 //A class can only implement an interface, not inherit an interface //implements cannot be changed to extends because a class can inherit a class, but a class cannot inherit an interface, which has no logical meaning. A class can implement an interface { public void f() { //I = 99; / / the value of the attribute defined in the error interface cannot be changed in the implementation class System.out.printf("i = %d\n", i); } } class B { } //A class can implement one or more interfaces while inheriting a parent class, but the extends keyword must precede the implements class C extends B implements It1, It2 { } public class TestInterface { public static void main(String[] args) { A aa = new A(); aa.f(); } }
interface It1 { int i = 10; void f(); } interface It2 { } //class A implements It1 //error class A is not abstract and does not cover the abstract method f() in It1 //{} abstract class B implements It1 // OK if a class implements only part of an interface's methods, the class must be declared as an abstract class { } class C implements It1 { public void f() // OK method rewrite, public must be added before //The access permission of method f in class C must be greater than or equal to the permission of method f in interface It1, otherwise an error will be reported { System.out.printf("AAAA"); } public void g() { } } class TestInterface_1 { public static void main(String[] args) { } }
class A { int i; //Property is not assigned, it will be assigned to 0 by default public void show() { System.out.printf("show-> %d\n", i); //i is the attribute i, where i is equivalent to this.i } public void f() { //After the local variable is defined, the garbage value is assigned by default. It cannot be used when it is not assigned (uninitialized). Otherwise, an error is reported int i; // There is no conflict between i and attribute i here //System.out.printf ("F - >% d \ n", i); / / error because i is a local variable, Java requires that the local variable must be initialized before use } public void g(int i) //i is a formal parameter i is also a local variable { this.i = i; System.out.printf("g-> %d\n", i); } } public class E { public static void main(String[] args) { A aa = new A(); //aa.g(99); aa.show(); } }
interface It { void f(); } class A implements It { public void f() { System.out.printf("AAAA\n"); } public void g() { } } class D { public static void main(String[] args) { //int i; //It tt = new It(); // error //It tt = new A(); //OK //tt.f(); //OK It it; it = new A(); //An interface object cannot be new, but a variable of interface reference type can be defined, //And point it to the object that implements the interface, so as to achieve the goal of polymorphism (just like the abstract class) it.f(); } }
//If a class implements only part of an interface's methods, it must be declared as an abstract class interface It1 { void f(); void g(); } abstract class A implements It1 // If the abstract is removed, an error will be reported { //public cannot be lost or changed to other modifiers //When a class wants to implement a method in an interface, it must add public before the return value of the method public void f() { System.out.printf("AAAA\n"); } } public class TestInter_1 { public static void main(String[] args) { } }

Function of interface

  • The same behavior of unrelated classes can be implemented through interfaces
    • For example, Java stipulates that all classes that can complete self replication must be implemented java.lang.Colneable Interface, but the interface is empty. There is nothing in the interface, just to play a flag role
  • Interface provides a platform for collaboration between different objects
    • Such as event handling
  • The interface can realize multiple inheritance, which makes up for the defect that a class can only inherit one
  • Interface is an important way for us to understand the function of a class
    • For example, the entire container framework of Java is built in the way of interface, and the classes that implement different interfaces accomplish different functions. The interface enables us to understand an important way of class functions

The difference between interface and abstract class

  • Methods in interfaces are not allowed to have method bodies, but abstract classes do
  • Java classes do not allow multiple inheritance, but interfaces allow multiple inheritance
    • Interface can implement multiple inheritance, that is, an interface can have multiple parent classes
    • However, Java classes only allow single inheritance, that is, a class can only have one parent class
package

Use of package

  1. package statement must be the first statement
  2. package zhangsan.lisi Representation: put all the classes in the file zhangsan.lisi The real names of all classes in this package and in this file will be the combination of package name and class name
  3. For example: the name of testpackage will change to zhangsan.lisi.TestPackage , instead of testpackage
  4. Javac - D is recommended at compile time TestPackage.java Try not to use javac TestPackage.java Because the latter has to manually create the package directory itself.
    javac -d . TestPackage.java , - D indicates that the package layer is automatically generated, and. Indicates that the package layer is created in the current directory
  5. If you do not run the program in the current path, you must ensure that the parent directory of the top directory of the class file is under classpath
//File name“ TestPackage.java " package zhangsan.lisi; //1 line public class TestPackage{ public static void main(String[] args){ new A().print(); } } class A{ public void print(){ System.out.println("AAAA"); } }

java zhangsan.lisi.TestPackage analysis

First, check whether there is a package named zhangsan/lisi (package is folder) in the current directory, and then check whether there is a package named zhangsan/lisi in the current directory zhangsan.lisi.TestPackage If there is no such class, the compiler will go to the path set by classpath to find one by one. If both lookups fail, an error occurs at run time.

Mutual access of different classes in the same package
//Mutual access of different classes in the same package //A.java files class A { public void f() { System.out.println("AAAA"); } } //B.java files class B { public static void main(String[] args) { A aa = new A(); aa.f(); } }

Execute the following command:

javac A.java B.java java B

Output: AAAA
Note: because class A and class B are in the same nameless package by default, they can access each other. As long as they are non private members, they can be accessed by another class in the same package

Mutual access of different package classes
//Mutual access of different package classes //Filename A.java package zhangsan.lisi; public class A { public void ma() { System.out.printf("AAAA\n"); } } //File name B.java package com.ruide public class B { public static void main(String[] args) { zhangsan.lisi.A aa = new zhangsan.lisi.A(); aa.ma(); } }

When compiling separately, you must first compile A.java, then B.java, otherwise you will make an error
It is recommended that two files be compiled together

javac -d . A.java B.java javac -d . B.java A.java //Either way
The first way to use classes in different packages:
package com.ruide; public class B { public static void main(String[] args) { zhangsan.lisi.A aa = new zhangsan.lisi.A(); //Use the full name of a class aa.ma(); } }
The second way to use classes in different packages:
package com.ruide; import zhangsan.lisi.*; public class B { public static void main(String[] args) { A aa = new A(); //Use import statement to import all classes in a package aa.ma(); } }
The third way to use classes in different packages:
package com.ruide; import zhangsan.lisi.A; public class B { public static void main(String[] args) { A aa = new A(); //Using import statement to import a specific class in a package aa.ma(); } } //Note: importing a parent's class does not automatically import a child's class //For example: import zhangsan. *; only all classes under the package of zhangsan will be imported, and the classes in the package of zhangsan sub package lisi will not be imported //Consider: Import java.awt . *; and import java.awt.event The difference between

Archive tool jar

  • Java archive tool is a multi-purpose archive and compression tool provided in JDK, which can merge and compress multiple files or directories into a single Java archive file
  • The main functions of jar files are as follows:
    • Publishing and using class libraries
    • Easy to combine and manage resources
Jar use example
  • Format: Jar - the package name to be generated by cvf.jar*
  • give an example:
    • jar -cvf c.jar * function: package all files in the current path, that is, all contents in the folder, into c.jar
    • jar -tf c.jar function: display the contents of the extracted file of c.jar under DOS
    • Function of jar - XF d: \ c.jar: extract the contents of d: \ c.jar to the current directory
How to use classes in jar package
  • Suppose there is a T.jar package now. If you want to access the classes in the T.jar package in any directory, you must also set the package name T.jar when setting the classpath, because T.jar is also equivalent to a directory
  • For example, if there is a T.jar under d:\share\java, the classpath must be set to d:\share\java\T.jar, which cannot be set to d:\share\java, or d:\share\java\T. otherwise, the classes in the T.jar package cannot be accessed under the non current directory

Different access modifiers

Different situations \ access specifiers public protected default private Same package √ √ √ √ Visit different classes of the same package √ √ √ Same package different class inheritance √ √ √ Different package inheritance √ √ Access to classes that have no relationship with different packages √

a key

  • In the same package, only private cannot be accessed by another class, and only private cannot be inherited
  • For two classes that have no relationship in different packages, only public members of the public class can be accessed by classes in another package
  • There are two classes with inheritance relationships in different packages. Only the public member of the public class and the protected member of the public class can be used internally by the subclass in another package. However, outside the subclass, only the public member of the parent class can be accessed through the subclass object name
package test.pac; public class A{ //You can change protected to public, but not private, or write nothing before void protected void f() { System.out.printf("AAAA\n"); } public static void main(String[] args) { A aa = new A(); aa.f(); } }
package zhangsan.lisi; import test.pac.*; class B extends A{ public void g(){ f(); //OK uses the protection method of the parent class inside the child class System.out.printf("GGGG\n"); } } class TestB{ public static void main(String[] args) { B bb = new B(); bb.g(); //bb.f(); //error } }

The above program proves that: for two classes with inheritance relationship in different packages, only the public member of the public class and the protected member of the public class can be used internally by the subclass in another package, but outside the subclass, only the public member of the parent class can be accessed through the subclass object name

package com.ruide; public class A //public can neither be removed nor changed to protected nor to promote { public void f() { System.out.printf("AAAA\n"); } }
package zhangsan.lisi; import com.ruide.*; class B { public void g() { A aa = new A(); //only com.ruide.A can be defined only when it is public com.ruide.A object aa.f(); //only com.ruide.A is public and f method is public } } class M { public static void main(String[] args) { } }

The above program proves that if a Class A is public, but its method members and domain members are non public, then we can still define the object aa of class A in the classes in other packages, but we cannot call the non public method members and non public domain members in aa through the class object aa

abnormal

Why exceptions are needed

Example 1: programming to assign the number input by keyboard to integer variable

import java.util.*; public class TestExcept_1 { public static void main(String[] args) { int i; Scanner sc = new Scanner(System.in); // System.in Show keyboard try { i = sc.nextInt(); //If the input is not a legal number and there is no exception handling, the program will terminate abnormally //The problems in this program cannot be solved through logical judgment. The exception handling mechanism provided by Java can solve this problem well System.out.printf("i = %d\n", i); } catch (Exception e) { System.out.printf("Illegal input data, program terminated!\n"); } } }
class A { int divide(int a, int b) { return a/b; } public void f() { g(); } public void g() { divide(6, 0); } } public class TestExcep_4 { public static void main(String[] args) { try { new A().f(); } catch (Exception e) { e.printStackTrace(); // Not only output error, but also output error path } } }

Exception handling mechanism

Definition of exception

Exception is an event that occurs during the operation of a program, which can interrupt the normal execution process of program instructions.

Exception handling mechanism (key)

  1. When there is a problem with the Java program running, the system will automatically detect the error and immediately generate an exception object corresponding to the error
  2. Then submit the exception object to the Java virtual machine
  3. The Java virtual machine automatically looks for the corresponding processing code to handle the exception. If it is not found, the program terminates
  4. Programmers can write their own code to catch possible exceptions and write code to handle the corresponding exceptions
import java.io.*; class A { public void f() throws IOException { throw new IOException(); //throw throws an exception } public void g() { throw new ArithmeticException(); } } public class TestExcep_1 { public static void main(String[] args) //throws IOException { A aa = new A(); try { aa.f(); } catch(IOException e) { } } }

Some common exceptions

  1. Null pointer exception of common exceptions
class Person { public int age; } public class TestNullPointerException { public static void main(String[] args) { Person p = null; System.out.println(p.age); //Runtime exception } }

The operation result is:

2. Common abnormal subscript out of bounds

public class TestIndexOutOf { public static void main(String[] args) { String friends[] = {"Lisa", "Bily", "Kessy"}; for (int i=0;i<5;i++) { System.out.println(friends[i]); } System.out.println("\nthis is the end"); } }

The operation result is:

3. Arithmetic exceptions of common exceptions

class A { int divide(int a, int b) { return a/b; } } public class TestArithExcep { public static void main(String[] args) { A aa = new A(); int i = aa.divide(3, 0); System.out.println(i); } }

The operation result is:

Classification of exceptions

  1. Error is a system error and programmers cannot handle these exceptions
  2. Exception is an exception that a programmer can catch and handle
  3. The subclass exception of RuntimeException is an exception that can be handled or not
  4. Any Exception inherited from Exception but not a RuntimeException subclass must be caught and handled
  • Error: generated and thrown by Java virtual machine, including dynamic link failure, virtual machine error, etc., which cannot be handled by Java program
  • Runtime Exception: exceptions generated by Java virtual machine at runtime, such as system errors such as division by 0, array subscript out of range, etc., are frequently generated, troublesome to handle, and have a great impact on program readability and running efficiency. Therefore, it is detected by the system, and the user does not need to handle them. The system will give them to the default exception handling (of course, the user can handle them if necessary)
  • Exception: a predictable problem in a general program, which may cause unexpected results. Therefore * * the java compiler requires the Java program to catch or declare all non runtime exceptions.

Exception handling steps:

try { Code block with possible exception } catch(ExceptionName1 e) { Handling measures when exception name1 exception is generated } catch(ExceptionName2 e) { Handling measures when ExceptionName2 exception is generated } ...... finally { Code that must be handled whether or not an exception is caught }

Catch and handle exceptions

The role of Finally

  • Whether or not an exception is thrown in the block specified by try, and whether or not the exception type of the catch statement is the same as that of the discarded exception, the code in finally will be executed
  • finally statement provides a unified exit for exception handling, so that the state of the program can be managed uniformly before the control process is transferred to other parts of the program
  • In general, resources can be cleared in the finally statement, such as closing open files, deleting temporary files, etc

throw

  • Throw is used to throw an exception
  • Format: throw new exception name (parameter);
  • If method f throws an A exception, then method f has two ways to handle the A exception
    • throws A
      Who calls f method, who handles A exception, f method does not handle A exception itself
    • try{...} catch(){...}
      Method f handles exception A by itself
  • The exception to be thrown must be a subclass of Throwable
    The exception to be thrown must be a subclass example of Throwable
//If the extensions throwable program is removed, an error will be reported class A extends Throwable { } class M { public void f() throws A { throw new A(); //The exception to be thrown must be a subclass of Throwable } } public class TestExcep_3 { public static void main(String[] args) { } }

throws

usage method

void f() throws A { ...... ...... }
  • throws A indicates that f method may throw A class A exception when calling F method. It is recommended that you should catch the class A exception that f method may throw when calling F method
  • throws A does not mean that the f method will throw A class A exception
    The throws A f method can also not throw A class A exception
  • throws A does not mean that when calling the f method, A class A exception must be caught
    • Suppose A is A RuntimeException subclass exception
    • Because the subclass exception of RuntimeException can be handled or not, the compiler allows you to call f method without handling the subclass exception of RuntimeException thrown by f method
  • It is highly recommended that you:
    • Handle all exceptions from throws
    • If an exception A has already been handled inside A method, do not throw A again
//This program proves that an F method throws A f method can not throw A exception, and the method calling F method can not handle A class exception class ER extends RuntimeException { } class A { public void f() throws ER { System.out.println("AAAA"); } } class M { public static void main(String[] args) { A aa = new A(); aa.f(); //Output: AAAA } }

Attention

  • Only one catch can be executed
  • It's possible that all the catch es are not executed
  • **First catch subclass exception and then catch parent exception
    • If you first catch the parent class exception and then catch the child class exception, an error will be reported at compile time
  • There can be no other code between catch and catch
  • The scope of exception thrown by overriding method cannot be greater than the scope of exception excluded by overriding method
//When a subclass covers a base method, the scope of exception thrown by the subclass method cannot be greater than the scope of exception thrown by the base method //Subclass methods can not throw exceptions, or only throw partial exceptions of the base method, but not exceptions other than the base method //Custom exception A class A extends Exception { } //Custom exception B class B extends Exception { } //Custom exception C class C extends Exception { } class M { void f() throws A, B{ } } class N extends M { void f() throws A, B //You can throw a or B, you can throw a or B, you can not throw C //That is, "when the subclass covers the base method, the scope of exception thrown by the subclass method cannot be greater than the scope of exception thrown by the base method" { } } class Test { public static void main(String[] args) { M m = new M(); N n = new N(); System.out.println("1111"); } }
//First catch subclass exception and then catch parent exception //If you first catch the parent class exception and then catch the child class exception, an error will be reported at compile time class A extends Exception { } class B extends A { } class C extends B { } class M { public void compare(int i, int j) throws A, B { if (i > j) throw new A(); else throw new B(); } } public class TestTryCatch { public static void main(String[] args) { M mm = new M(); try { mm.compare(-4, 1); } catch (B bb) //Subclass exception { System.out.println("The left side cannot be smaller than the right side"); } catch (A aa) //Parent exception { System.out.println("The left side cannot be larger than the right side"); } } }

Abnormal advantages and disadvantages

Advantages of abnormality

Programs without error handling:

{ openTheFile; determine its size; allocate that much memory; read-file; closeTheFile; }

Handling errors in the normal way

openFiles; if (theFilesOpen) { determine the length of the file; if (gotTheFileLength) { allocate that much memory; if (gotEnoughMemory) { read the file into memory; if (readFailed) errorCode = -1; else errorCode = -2; } else errorCode = -3; } else errorCode = -4; } else errorCode = -5;

To deal with the problems of errors in the normal way:

  • If you look at the previous program, you will find that most of your energy is spent on error handling
  • Only take into account the mistakes that can be thought of, and can't deal with other situations
  • Program readability is poor, a large number of error handling code mixed in the program
  • The amount of error return information is too small to know the error condition or cause more accurately

Advantages of abnormality
Handle errors in the form of exceptions:

{ try { openTheFile; determine its size; allocate that much memory; read-file; closeTheFile; } catch(fileopenFailed) {dosomething;} catch(sizeDetermineFailed) {dosomething;} catch(memoryAllocateFailed) {dosomething;} catch(readFailed) {dosomething;} catch(fileCloseFailed) {dosomething;} finally {dosomething;} }

advantage:

  • Forcing programmers to consider the security and robustness of programs
  • Enhance the programmer's controllability of the program
  • Good for code debugging
  • Separate error handling code from regular code
    be careful:
  • Exceptions do not necessarily make the logic of the program clearer
    • Because sometimes we have to write code to catch exceptions, the logic of the program may be very confusing
  • Exceptions don't solve all problems

25 June 2020, 22:40 | Views: 1780

Add new comment

For adding a comment, please log in
or create account

0 comments