Q: What are the four features of object-oriented programming and what do they mean?

The first four characteristics are: encapsulation, inheritance, polymorphism, abstraction

What is encapsulation?

The idea is to combine the properties and operations (or services) of an object into a single entity, hiding the internal implementation details of the object as much as possible.

Encapsulation encapsulates processes and data, and data can only be accessed through defined interfaces.

The common point is to hide information to provide an interface for others to use, so that others do not directly manipulate properties or methods.

What is inheritance?

Inheritance is the derivation of a new class from an existing class, which can absorb the data attributes and behavior of the existing class and extend the new capabilities.

The parent class is also called superclass or base class, and the child class is also called derived class. A superclass is a generalization of a subclass, and a subclass is a specialization of a superclass.

Cast up: Casting an object referenced by a subclass to its parent type is called an upcast. In layman’s terms, a subclass object is converted into a superclass object. Here the superclass object can be an interface

Cast down: Casting an object referenced by a parent class to a subclass type is called a cast down. Case 1: If the object referred to by the parent class refers to the object referred to by the child class, then it is safe during the downward transition. You can’t make an error when you compile.

What is polymorphism?

The concept of polymorphism is “one interface, many methods”

Polymorphism refers to procedures defined in the reference variable is pointing to the specific type and referenced by the variable from method calls are not sure when programming, but during the program is run to determine, that is, a reference variable STLL can point to which class instance object, the reference variable from method calls the method to realize exactly is which class, It must be decided during the running of the program.

Overriding methods and Overloading are different manifestations of Java polymorphism

Method overloading: a unified class with multiple methods of the same name. It doesn’t matter the number of arguments, the order, the different types of return values, or the modifiers

Method override: a subclass inherits a method of the same name from its parent. The method name and argument must be the same and the return value type must be the same as the return value type of the method of the parent class

What is abstraction?

Abstraction is the process of parsing an object into its properties instead of representation. To pull is to pull away; Image representation, that is, the represented part

The abstract keyword abstract can modify a class or method abstract method: a method that has no method body in a class is an abstract method. Abstract return value type method name ();

Abstract classes: Classes that contain abstract methods are called abstract classes. Abstract class name {}

1 When the abstract keyword is used to modify a class, the class is called abstract. When we use abstract to describe a method, the method is called abstract. Classes containing abstract methods must be declared as abstract classes, the abstract classes must be inherited, and the abstract methods must be overridden. 3 Abstract classes cannot be instantiated. Abstract methods only need to be declared, but do not need to implement some function.

Interface features: A) Interfaces generally define constants and abstract methods. An abstract class may contain abstract methods or non-abstract methods, but a class with abstract methods must be an abstract class. An abstract method cannot have a method body. B, In interface, methods can only define abstract methods and are Public by default, while constants are Public static final. C) a class can implement multiple unrelated interfaces (as opposed to inheritance). D) Interfaces can inherit from other interfaces and add new properties and abstract methods. E. The public modifier must be used when implementing interface methods in a class.

Interface and abstract class differences: (1) similarity A, both are abstract classes, can not be instantiated. B) The Interface implementation class and its Abstrct class subclass must implement the declared abstract method.

(2) Differences

A) implements interface; B) implements abstract class;

B) a class can implement multiple interfaces, but a class can only inherit one Abstract class.

C) interface emphasizes the implementation of a particular function. D) Abstract class emphasizes ownership.

D) The interface implementation class and the Abstrct class subclass must implement the corresponding abstract method.

E, Interface is completely abstract. It can only declare methods, and only pulic methods. It cannot declare private or protected methods, method bodies, or instance variables.

Q: The difference between String, StringBuffer, and StringBuilder

String: String constant. StringBuffer and StringBuilder are character buffer variables. StringBuffer and StringBuilder are identical except that most methods in StringBuffer are thread-safe and are modified with the synchronized keyword, which StringBuilder does not. Can be considered thread unsafe. StringBuilder was added in JDK1.5.

Note: From JDK1.5 onwards, concatenation (+) with string variables is implemented internally as a StringBuilder, whereas previously it was implemented as a StringBuffer.

1. String objects are immutable. Once a String is created, the series of characters contained in it cannot be changed until the object is destroyed. StringBuilder and StringBuffer strings are mutable, but StringBuffer strings are thread-safe, while StringBuilder strings are not thread-safe. StringBuffer is preferred. StringBuilder is preferred if it is non-multithreaded and there is a lot of string concatenation, insertion, and deletion. After all, the String class does String concatenation by creating temporary variables, which is not very memory efficient, but StringBuilder does the ultimate operation through JNI.Copy the code

StringBuilder > StringBuffer > String

String a=”” and String a=new String(“”)

  1. String is an object. Since the default value of an object is NULL, the default value of a String is also null; But it’s also a special kind of object that has some properties that other objects don’t.

  2. New String() and new String(” “) both declare a new empty String, an empty String, not null;

Let’s start with the simple concept of a constant pool. The constant pool is the data that is identified at compile time and stored in a compiled.class file. It includes constants in classes, methods, interfaces, and so on, as well as string constants.

Strings created with new String() are not constants and cannot be determined at compile time, so strings created with new String() do not go into the constant pool; they have their own address space.

  1. About equals() and ==:

This simply compares the Unicode sequences of two strings to be identical, returning true if they are; And == compares whether the addresses of two strings are the same, that is, whether they are references to the same string.

Data types in Java can be divided into two types: 1. Basic data types, also known as primitive data types. Byte, short, char, int, long, float, double, Boolean comparison between them, the double equal sign (= =), and compare their values. 2. Composite data Types (Classes)

When they compare (==), they are comparing their memory location, so unless they are the same new object, their comparison result is true, otherwise the comparison result is false. All JAVA classes inherit from the base class Object. The equals method is defined in the base class Object. The initial action of this method is to compare the memory addresses of objects, but it is overridden in some libraries. Among these classes, equals (String,Integer,Date) has its own implementation, rather than comparing the addresses of the classes in the heap. Comparing equals between compound data types is based on the address of their memory location without overwriting the equals method, since Object’s equals method also uses the double equal sign (==) to compare them. So the result is the same as the double equal sign (==).

Q: What is the meaning of packing and unpacking?

In Java, boxing and unboxing refer to automatic conversions between basic data types and wrapper types, which is convenient for developers. Developers can also do type conversions manually without using it. This type conversion is at compile time.

Q: What is the difference between int and Integer?

The big difference between int and INTEGER is the difference between the base data type and its wrapper class:

Int is a primitive type that holds values directly, while INTEGER is an object that is referred to by a reference

Q: What runtime exceptions have you encountered? What does the exception handling mechanism know?

When a program goes wrong, there are three possible errors:

  • Syntax errors: Such as the lack of necessary punctuation marks, keyword input errors, data type mismatch, etc. During the process of compiling the program, the compiler will list the detected syntax errors as prompts, so they are also called compilation errors.
  • Runtime errors: such as null pointer exception, array out of bounds, divisor zero, database connection failure, etc., forcing the program to terminate, with specific conditions.
  • Logic error: syntactically valid, but logically incorrect. This kind of problem is not easy to debug.

The Java exception handling mechanism in this context mainly refers to handling runtime errors.

A. Hrowable inheritance hierarchy can be divided into two categories: Error and Exception.

Error

Error: An exception that cannot be recovered by the program, indicating a serious problem in running the application.

  • Occurs when the VM itself or when the VM tries to execute an application, such as Virtual MachineError (Java Virtual machine running error) or NoClassDefFoundError (class definition error).

  • It is an untraceable exception, that is, it does not force the programmer to handle it, and even if it does not handle it, syntax errors will not occur.

    Exception

(Exception) : Indicates a program

Exceptions that can be recovered represent exceptions that can be handled by the program itself. There are two main categories:

  • RuntimeException
    Copy the code

    Runtime exception: An exception caused by a problem in the program itself.

    • Such as NullPointerException (null pointer exception), IndexOutOfBoundsException (subscript cross-border exception).
    • Belongs to an untraceable exception.
  • Non-runtime exception: An exception caused by a problem outside the program.
    • Exceptions other than RuntimeException, such as FileNotFoundException (file does not have an exception).
    • Is a traceable exception that forces the programmer to handle it, or a syntax error occurs if it is not handled.

B. Exception handling mechanism

(1) Catch exceptions: the system automatically throws exceptions

  • Try catch exception: Used to monitor, if an exception occurs, the object generated by the exception class is thrown and execution immediately ends, and the catch block is turned to exception handling.
  • catch
    Copy the code

    Handling exceptions: If the exception object thrown is an exception class defined ina catch, the program continues to run in the corresponding section of the catch, or in the finally block. Common methods:

    • LLDB etMessage() : Returns a short description of the exception object
    • E.tostring () : Gets details about the exception object
    • E.prinintstacktrace () : Prints the exception object and its trace information on the console
  • finally
    Copy the code

    Final processing: Statements ina finally block are executed whether or not exceptions are caught or handled. A finally block is not executed in four special cases:

    • An exception occurred in the finally statement block

    • System.exit() was used in the previous code to exit the program

    • The thread on which the program resides dies

    • Shut down the CPU

      try {

      // Program code that may be abnormalCopy the code

      } catch (exception class 1 exception variable) {

      // Catch and handle the exception type Type1 thrown by a tryCopy the code

      } Catch (exception class 2 exception variable) {

      // Catch and handle the exception type Type2 thrown by a tryCopy the code

      } finally {

      // Block of statements that will be executed whether or not an exception occursCopy the code

      }

Note:

  • No other code can be inserted between a try, catch, and finally
  • There can be more than one catch, and only one try and finally
  • A try must be followed by at least one of the catch and finally

(2) Throw exception: The exception object is explicitly thrown in the method, and then the exception is thrown up the call hierarchy to be handled by the calling method.

  • Throws: Declares a thrown exception after the method name and before the exception type
  • Throw: Throws an exception, usually inside the method body

(3) Custom exception: inherits the Execption class or its subclasses. The implementation steps are as follows:

  • Declare a custom Exception class and inherit Exception, overriding methods such as getMessage()

  • Throws a throws declaration in the method header that may throw exceptions

  • Create a custom exception class object in the appropriate place in the method body and throw the exception

  • When this method is called, exceptions that might arise are caught and handled

    Class MyException extends Exception {class MyException extends Exception {

     String message; 
    
     public MyException(String ErrorMessagr) { 
        super(ErrorMessagr) ;
     }
    
     public String getMessage() {
        return message;
     }
    Copy the code

    }

    public class Demo {

    public static void main(String[] args) { //4. Catch and handle try {test() when calling a method; } catch (MyException e) { System.out.println(e.getMessage()); e.printStackTrace(); Public static void test() throws MyException{try {int I = 10/0; System.out.println("i="+i); } catch (ArithmeticException e) { //3. Throw new MyException("This is MyException") if appropriate; }}Copy the code

    }

Q: What is reflection? What are its functions and applications?

Java base generics & Reflection

A. generics

  • Parameterized type is a new feature in JDK1.5, essentially parameterized type, that is, the data type to be operated on is specified as a parameter, and the specific type is specified by passing the parameter.

  • Bonus: Safe and simple. This is reflected in providing strong type checking at compile time, rather than waiting until run; Class type casts can be avoided; Improve code readability.

    List List = new ArrayList(); list.add(“hello”); List list = new ArrayList(); String s = (String) list.get(0); list.add(“hello”); String s = list.get(0);

The above example also shows that the use of generics in collection classes is common and dynamic compared to arrays.

  • Type: depending on the location of the creation, it can be
    • Generic class: Public class < generic type 1,… >
    • Generic methods: public < generic type 1,… > Return type method name (generic type 1 parameter name 1…)
    • Public interface Interface name < generic type 1,… >

Here are some examples.

Public class ObjectTool<T> {private T obj; public T getObj() { return obj; } public void setObj(T obj) { this.obj = obj; Public static void main(String[] args) {ObjectTool<String> ot1 = new ObjectTool<String>(); ot1.setObj(new String("Jiwenjie")); System.out.println(" name: "+ ot1.getobj ()); // Name is: Jiwenjie ObjectTool<Integer> ot2 = new ObjectTool<Integer>(); ot2.setObj(new Integer(21)); Println (" age is: "+ ot2.getobj ()); Public class ObjectTool {public <T> T show(T T) {if (T! = null){ return t; }else{ return null; Public class ObjectToolDemo {public static void main(String[] args) {ObjectTool ot = new ObjectTool(); System.out.println(ot.show("Jiwenjie")); //Jiwenjie System.out.println(ot.show(21)); Public interface ObjectTool<T,U> {void show(T T,U U); } class ObjectToolTest implements ObjectTool<String,Date> { @Override public void show(String str,Date date) { System.out.print(str); System.out.print(date); Public class ObjectToolDemo {public static void main(String[] args) {ObjectToolTest test = new ObjectToolTest(); test.show("Hello",new Date()); //Hello current time}}Copy the code
  • Type qualification for generic variables: With the extends keyword, formal parameters are qualified

For example, public Class ObjectTool accepts only the arguments of the Number class or its subclasses

  • The wildcard? Delimit: with the extends and super keywords, delimit the actual parameters
    • Not restricted List
      : equivalent to List
    • List
      : represents an undefined parameter type, but must be the type of the Number class or its subclasses
    • List
      : indicates that the parameter type is uncertain, but must be the type of the Number class or its parent

Such as the List <? extends Number> list =new ArrayList(); Represents a List of elements whose objects are all INTEGERS

  • Generic erase: Clears information about generic type parameters and adds type checking and conversion methods if necessary. Generic Java code -> plain Java code

    Class Pair {private T value; public T getValue() { return value; } public void setValue(T value) { this.value = value; }} class Pair {private Object value; public Object getValue() { return value; } public void setValue(Object value) { this.value = value; }}

  • Restrictions on use:

    <int, char> p = new Pair<>(8, ‘a’); // error Pair<Integer, Character> p = new Pair<>(8, ‘a’); // ok

    Public class MobileDevice {private static T OS; // error }

    Casts cannot be cast on parameterized types except unbounded wildcard types List li = new ArrayList<>(); List<? > list = li; // ok List ln = (List) li; // error

    // Can’t use instanceof for parameterized types, Public static void rtti(List List) {if (List instanceof ArrayList) {// error} if (List instanceof) ArrayList<? >) { // OK } }

    [] arrayOfList = new ArrayList[3]; // error

    Class QueueFullException extends Throwable {} class QueueFullException extends Throwable {} class QueueFullException extends Throwable { error

    public static <T extends Exception, J> void execute(List jobs) { try { } catch (T e) { // error } }

    Public class Example {// error public void print(List List) {} public void print(List) {} public void print(List) list) {} }

Key points:

B. reflection

Meaning: In the running state, any class can know all its attributes and methods, and any object can call any of its methods and attributes.

function

Dynamic:

  • Determine which properties and methods any class has at run time

  • Determine the class to which any object belongs at run time

  • Constructs an object of any class at run time

  • Call a method of any object at run time

  • Generating dynamic proxies

    java.lang.Class

: implements reflection

basis

  • why

    • The JVM creates a corresponding Class object for each Class and stores it in a.class file of the same name. About class loading mechanisms
    • None of the classes in the Java reflection package java.lang.Reflect have a public constructor, and you can only get instances of those classes through the Class Class
  • Method to get a Class object

    • .class: Base types are available by class type

    • Object.getclass () : Through Object instances, note that basic data types are not available

    • Class.forname () : Through the fully qualified name of the Class, note that the base data type is not available

      Class c1 = Test.class; Class c2 = test.getClass(); / / the test is a test Class c3 = Class. An object of the Class class.forname (” com. Catchu. Me. Reflect. Test “);

  • java.lang.reflect.Member
    Copy the code

    : Object of reflection operation. Three implementation classes are provided to change object state at run time:

    • Constructor: A Constructor in the corresponding class member
    • Field: variable in the corresponding class member
    • Method: The Method in the corresponding class member

Class provides multiple methods to get the Constructor, Field, and Method of a given Class, as shown below:

Security issues. Using reflection requires that the program be run in an environment with no security restrictions. This is a problem if a program must run in an environment with security restrictions, such as an Applet.

Code issues. Because reflection allows code to perform operations that are not normally allowed (such as accessing private properties and methods), using reflection can have the unintended side effect of making code functional errors and reducing portability. Reflecting code breaks abstractness, so when the platform changes, it is possible for the code to behave as well.

Q: What is an inner class? What does it do? What is the difference between a static inner class and a non-static inner class?

To some extent, an exposed static inner class is equivalent to a normal class. Static inner classes contain only the relation to the outer class, reducing the namespace and adding an outer class name to the full class name. There are essentially two separate classes, and the JVM does not know their inclusion relationship.

(1) Static inner class: it is equivalent to the static member of the external class, using static modification of the inner class, it belongs to the external class, used as an independent external class.

(2) Member internal class: it is equivalent to the common member of the external class, belonging to the specific object of the external class. When defining it, we need to create the external class object first, and then create its instance.

(3) Local inner class: defined in the body of a method, it tends to be used only briefly as a method, accessing only local variables with final modifications.

(4) Anonymous inner class: it is also defined in the method body, but does not have a specific name, has great flexibility, and works in nature and local inner class similar.

Q: What are the meanings of final, finally, Finalize ()?

The Java keyword final has the meaning “this cannot be changed” or “final state” and can be used to modify non-abstract classes, non-abstract class member methods, and variables.

  • Final classes cannot be inherited, there are no subclasses, and methods in final classes are final by default.
  • Final methods cannot be overridden by subclass methods, but can be inherited.
  • Final member variables represent constants and can only be assigned once, after which the value does not change.
  • Final cannot be used to modify constructors.

Note: Private member methods of a parent class cannot be overridden by subclass methods, so methods of private type are final by default.

finally

Used for the processing part of exception catching.

Finalize:

Finalize is the method name, and Java technology allows you to use the Finalize () method to do the necessary cleanup before the garbage collector purifies objects from memory. This method is called when the garbage collector confirms that an object is not referenced. It is defined in the Object class, so all classes inherit from it. Subclasses override the Finalize () method to collate system resources or perform other cleanup tasks. The Finalize () method is called on an object before the garbage collector removes it.

Q: What are the common methods of Object?

(1) Clone method to realize shallow replication of objects. This method can only be called if the Cloneable interface is implemented.

(2) getClass method, used to get the runtime type

(3) toString method, generally overridden in the subclass, used more

(4) Finalize method, which is used to release resources. This method is rarely used because it is impossible to determine when it will be called.

== == == == == == == Subclasses typically override this method.

(6) The hashCode method is used to reduce the number of times the equals method is used in the search. This method can be used in some collections with hash capabilities.

(7) The current thread must be the owner of the object, that is, it has the lock of the object. The wait method waits until either the lock is acquired or it is interrupted. Wait sets a timeout interval and returns if no lock has been acquired within the specified time.

(8) Notify method, wake up a thread waiting on the object

(9) notifyAll method, which wakes up all threads waiting on the object.