polymorphism
-
Polymorphism means that the same method can behave in many different ways depending on the object being sent
-
The actual type of an object is determined, but there are many types of references that can point to objects
-
Conditions for the existence of polymorphism
- have an inheritance relationship
- Subclass override superclass method
- Parent class reference points to child class object
-
Polymorphism is polymorphism of methods, not polymorphism of properties
public class Person { public void run(){ System.out.println("run"); } }
public class Student extends Person{ @Override public void run() { System.out.println("song"); } public void eat(){ System.out.println("eat"); } }
public class Application { public static void main(String[] args) { //The actual type of an object is deterministic, the reference type that can be pointed to is indeterminate Student s1 = new Student(); //The reference of the parent class points to the child class Person s2 = new Student(); Object s3 = new Student(); /* Student The methods that can be called are all own or inherited from the parent class Person The parent type, which can point to the subclass, but cannot call methods unique to the subclass */ s2.run();//The subclass overrides the superclass's method and executes the subclass's method s1.run(); s1.eat(); //s2.eat(); cannot be called ((Student)s2).eat(); } }
Polymorphism Notes: 1.Polymorphism is polymorphism of methods, not polymorphism of properties 2.The parent class is related to the child class Type conversion exception ClassCastException! 3.Existence conditions: inheritance relationship, methods need to be rewritten, parent class references point to subclass objects cannot be overridden: 1.static A method belongs to a class, it does not belong to an instance 2.final constant 3.private method
instance of and type conversion
instance of determines what type an object is
public class Application { public static void main(String[] args) { //Object-->Person-->Student Object object = new Student(); System.out.println(object instanceof Student);//true System.out.println(object instanceof Person);//true System.out.println(object instanceof Object);//true System.out.println(object instanceof Teacher);//false System.out.println(object instanceof String);//false System.out.println("==========================="); Person person = new Student(); System.out.println(person instanceof Student);//true System.out.println(person instanceof Person);//true System.out.println(person instanceof Object);//true System.out.println(person instanceof Teacher);//false //System.out.println(person instanceof String);//Compile error }
type conversion
public class Student extends Person{ public void go(){ System.out.println("go"); } }
public class Application { public static void main(String[] args) { //Conversion between types: parent (high) child (low) //When a subclass is converted to a parent class, it may lose some of its original methods Person student = new Student(); //Convert the student object to the Student type, and you can call the Student type method. ((Student)student).go(); } } /* 1.Parent class reference points to child class object 2.Convert subclass to parent class, upcast; free conversion 3.Convert parent class to subclass, downcast; cast 4.Invocation of convenience methods */
static keyword
public class Student { private static int age;//static variable private double score;//non-static variable public void run(){ } public static void go(){ } public static void main(String[] args) { Student s1 = new Student(); /* System.out.println(Student.age); System.out.println(s1.age); System.out.println(s1.score); */ Student.go(); s1.run(); } }
public class Person { { //code block (anonymous) System.out.println("anonymous code block"); } static { //static code block System.out.println("static code block"); } public Person() { System.out.println("Construction method"); } public static void main(String[] args) { Person person1 = new Person(); System.out.println("========"); Person person2 = new Person(); //output /* static code block anonymous code block Construction method ======== anonymous code block Construction method */ } }
//static import package import static java.lang.Math.random; public class Test { public static void main(String[] args) { System.out.println(random()); } }
abstract class
- The abstract modifier can be used to modify a method or a class. If a method is modified, then the method is an abstract method; if a class is modified, then the class is an abstract class
- Abstract classes can have no abstract methods, but classes with abstract methods must be declared as abstract classes
- Abstract class, cannot use the new keyword to create objects, it is used for subclasses to inherit
- Abstract method, only method declaration, no method implementation, it is used for subclasses to implement
- If a subclass inherits an abstract class, it must implement the abstract methods that the abstract class does not implement, otherwise the subclass must also be declared as an abstract class
//abstract abstract class class can only inherit single interface can inherit multiple public abstract class Action { //Abstract method, only the name of the method, no implementation of the method public abstract void doSomething(); } /* 1.The abstract class cannot be new, it can only be realized by subclasses; constraints 2.Ordinary methods can be written in abstract classes 3.Abstract method must be in abstract class The essence is restraint Constructor exists in abstract class */
//All methods of an abstract class, inheriting its subclasses, must implement his methods public class A extends Action{ @Override public void doSomething() { System.out.println("do"); } }
interface
Ordinary classes: only concrete implementations
Abstract class: both concrete implementation and specification (abstract method)
Interface: only specs! Constraint and Implementation Separation: Interface-Oriented Programming
An interface is a specification that defines a set of rules that embody the real-world "if you are... you must be able to..." mentality. Example: If you are a bird, you must be able to fly.
The essence of an interface is a contract, just like the laws of our world. After the formulation is completed, everyone will abide by
The essence of object-oriented is the abstraction of objects, and the interface that best reflects this is the interface
//An interface needs to have an implementation class public interface UserService { //constant public static final int age = 99; //All methods defined in the interface are actually abstract by default public abstract void add(String name); void delete(String name); void update(String name); void query(String name); }
public interface TimeService { void timer(); }
//class implements interface //A class that implements an interface needs to override the methods in the interface //Implementing Multiple Inheritance Using Interfaces public class UserServiceImpl implements UserService,TimeService{ @Override public void add(String name) { } @Override public void delete(String name) { } @Override public void update(String name) { } @Override public void query(String name) { } @Override public void timer() { } }
effect: 1.constraint 2.Define some methods for different people to implement 3.public abstract 4.public static final 5.The interface cannot be instantiated, there is no constructor in the interface 6.implements Can implement multiple interfaces 7.You must override the methods in the interface
inner class
An inner class is to define another class inside a class. For example, if a class B is defined in class A, then class B is called an inner class relative to class A, and class A is an external class relative to class B.
- member inner class
- static inner class
- local inner class
- anonymous inner class
public class Outer { private int id = 123; public void out(){ System.out.println("This is the method of the outer class"); } public class inner{ public void in(){ System.out.println("This is the method of the inner class"); } //Get private properties of outer class public void getId(){ System.out.println(id); } } }
public class Application { public static void main(String[] args) { Outer outer = new Outer(); //Instantiate inner class from outer class Outer.inner inner = outer.new inner(); inner.getId(); } }
abnormal
In actual work, the situation encountered cannot be perfect. For example, for a module you wrote, the user input may not meet your requirements, your program wants to open a certain file, the file may not exist or the file format is wrong, you want to read the data of the database, the database may be empty . Our program is running and the memory or hard drive may be full.
During the running process of the software program, it is very likely to encounter these abnormal problems just mentioned. We call it abnormal. English is: Exception, which means exception. These, exceptions, or exceptions, how can the programs we write make reasonable processing, so as not to cause the program to crash.
Exceptions refer to various situations that occur unexpectedly during program operation, such as: file cannot be found, network connection failure, illegal parameters, etc.
An exception occurs during program execution, and it affects the normal program execution flow.
There are three types of exceptions in Java:
- Checked Exceptions: The most representative checked exceptions are those caused by user errors or problems, which the programmer cannot foresee. For example, when opening a file that does not exist, an exception occurs. These exceptions cannot be simply ignored at compile time.
- Runtime Exceptions: Runtime exceptions are exceptions that may be avoided by the programmer. In contrast to checked exceptions, runtime exceptions can be ignored at compile time.
- Errors: Errors are not exceptions, but problems outside the programmer's control. Errors are usually ignored in code. For example, when the stack overflows, an error occurs and they cannot be checked by the compilation
Java treats exceptions as objects and defines a base class java.lang.Throwable as the superclass of all exceptions.
Many exception classes have been defined in the Java API, and these exception classes are divided into two categories, Error and Exception.
Error
Error class objects are generated and thrown by the Java virtual machine, most errors have nothing to do with the actions performed by the code writer
An OutOfMemoryError occurs when the JVM no longer has the necessary memory resources to continue the operation. When these exceptions occur, the Java virtual machine generally chooses to terminate the thread
It also occurs when the virtual machine tries to execute the application, such as class definition error (NoClassDefFoundError), connection error (LinkageError). These errors are untraceable because they are outside the control and processing power of the application, and most are not allowed to occur while the program is running.
Exception
There is an important subclass RuntimeException (runtime exception) in the Exception branch
- ArrayIndexOutOfBoundsException (array index out of bounds)
- NullPointerException (null pointer exception)
- ArithmeticException
- MissingResourceException (missing resource)
- ClassNotFoundException (class not found), these exceptions are unchecked exceptions, and the program can choose to capture and handle them, or not to handle them.
These exceptions are generally caused by program logic errors, and the program should avoid the occurrence of such exceptions as much as possible from a logical point of view;
The difference between Error and Exception: Error is usually a catastrophic fatal error that cannot be controlled and handled by the program. When these exceptions occur, the Java virtual machine generally chooses to terminate the thread; Exception can usually be handled by the program, and These exceptions should be handled as much as possible in the program.
exception handling mechanism
- Throw an exception
- catch exception
- Five keywords for exception handling
- try,catch,finally,throw,throws
public class Test { public static void main(String[] args) { new Test().test(1,0); } //Suppose this method cannot handle this exception. method throws exception public void test(int a,int b) throws ArithmeticException{ if (b==0) {//throw throws throw new ArithmeticException();//Actively throw exceptions, generally used in methods } } } /* int a = 1; int b = 0; //Suppose you want to catch multiple exceptions: small to large //Shortcut: CTRL alt + t try {//try Monitoring area System.out.println(a / b); }catch (ArithmeticException e){//catch(the type of exception you want to catch) catch the exception System.out.println("An exception occurred in the program"); }finally {//handle the aftermath System.out.println("finally"); } //can not finally, */
custom exception
Using Java's built-in exception classes can describe most of the exceptions that occur during programming. In addition, users can also customize exceptions. User-defined exceptions, just inherit the Exception class.
Using a custom exception class in a program can be roughly divided into the following steps
- Create custom exception class
- Throws an exception object through the throw keyword in a method
- If the exception is handled in the method that currently throws the exception, you can use the try-catch statement to capture and handle it; otherwise, specify the exception to be thrown to the caller of the method through the throws keyword at the declaration of the method, and proceed to the next step.
- Catch and handle exceptions in the caller of the exception method.
//custom exception class public class MyException extends Exception{ //Pass a number greater than 10, throw an exception private int detail; public MyException(int a) { this.detail=a; } //toString: abnormal print information @Override public String toString() { return "MyException{" + "detail=" + detail + '}'; } }
public class Test1 { //There may be exception methods static void test1(int a ) throws MyException { System.out.println("The parameter passed is"+a); if (a>10){ throw new MyException(a); } System.out.println("ok"); } public static void main(String[] args) { try { test1(11); } catch (MyException e) { System.out.println("MyException=>"+e);; } } }
Summarize
- When dealing with running exceptions, use logic to reasonably avoid and assist with try-catch processing
- After multiple catches, you can add a catch (Exception) to handle exceptions that may be missed
- For uncertain code, try-catch can also be added to handle potential exceptions
- Try to handle exceptions as much as possible, don't simply call printStackTrace() to print the output
- How to deal with exceptions depends on different business requirements and exception types.
- Try to add finally block to release occupied resources