1. Java object orientation

1.1 Classes and objects

1.1.1. The difference between object-oriented and procedural

1, process oriented: Process oriented performance is higher than object oriented. Because class invocation requires instantiation, which costs a lot and consumes resources, process-oriented development is generally adopted when performance is the most important factor, such as single-chip microcomputer, embedded development, Linux/Unix, etc. However, process orientation is not as easy to maintain, reuse, and extend as object orientation.

2, object-oriented: object-oriented easy to maintain, easy to reuse, easy to expand. Because object-oriented has the characteristics of encapsulation, inheritance and polymorphism, it is possible to design a low coupling system, which makes the system more flexible and easier to maintain. However, object-oriented performance is lower than procedural performance.

This is not the root cause. Procedural orientation also requires allocating memory and calculating memory offsets. The main reason for Java’s poor performance is not that it is an object-oriented language, but that Java is a semi-compiled language, and the final execution code is not binary mechanical code that can be executed directly by the CPU.

Most procedural languages are compiled directly into mechanical code for execution on the computer, and some other procedural scripting languages do not necessarily perform better than Java.

1.1.2. Can Constructor Constructor be override?

Constructor cannot be overridden, but can overload, so you can see situations where there are multiple constructors in a class.

1.1.3. The role of defining a do-nothing, no-arguments constructor in Java

If a Java program calls a superclass-specific constructor without super() before executing a subclass constructor, it will call the “no-arguments constructor” in the superclass. Therefore, if only the constructor with arguments is defined in the parent class and no super() is used to call the specific constructor in the parent class in the constructor of the child class, an error will occur at compile time because the Java program will not find a constructor without arguments in the parent class to execute. The solution is to add a constructor to the parent class that does nothing and takes no arguments.

1.1.4. What are the differences between member variables and local variables?

1. Syntactically, member variables belong to classes, while local variables are variables or method parameters defined in code blocks or methods. Member variables can be modified by modifiers such as public,private, and static, while local variables cannot be modified by access-control modifiers or static. However, both member variables and local variables can be modified by final.

If a member variable is static, it belongs to the class. If a member variable is static, it belongs to the instance. Objects live in heap memory and local variables live in stack memory.

3. From the perspective of the memory survival time of variables: Member variables are part of the object, and they exist with the creation of the object, while local variables disappear automatically with the invocation of the method.

4. If a member variable is not assigned an initial value: it is automatically assigned to the default value of the type (except for the case that final modified member variables must also be explicitly assigned), while local variables are not automatically assigned.

1.1.5. What operator is used to create an object? How is an object entity different from an object reference?

The new operator creates the object instance (which is in heap memory) and the object reference points to the object instance (which is in stack memory). An object reference can point to zero or one object (a string can be tied to either a balloon or a balloon); An object can have n references to it (a balloon can be tied with n strings).

1.1.6. What does a class constructor do? If a class does not declare a constructor, does the program execute correctly? Why is that?

The main function is to complete the initialization of the class object. Yes. Because a class will have a default constructor that takes no arguments even if it does not declare a constructor. If we add class constructors ourselves (with or without arguments), Java doesn’t add default parameterless constructors, and we can’t just new an object without passing arguments, so we’ve been unwittingly using constructors. This is why we create objects with parentheses (because we call the constructor without arguments). If we override a constructor with arguments, remember to include the non-argument constructor as well (whether or not it is used), as this will help us create objects with fewer bugs.

1.1.7. What are the properties of constructors?

1. The name is the same as the class name. 2, there is no return value, but the constructor cannot be declared with void. 3, automatically execute when generating the object of the class, without calling.

1.1.8. The subclass constructor is called without arguments before the subclass constructor is called.

Help subclasses do initialization work.

1.1.9. What is the difference between equality of objects and equality of references to them?

The equality of objects compares whether the contents in memory are equal. Reference equality, on the other hand, compares whether the memory addresses they point to are equal.

1.2. Three characteristics of object orientation

1.2.1. The encapsulation

Encapsulation refers to hiding an object’s state information (that is, its properties) inside the object, denying external objects direct access to the internal information of the object. However, you can provide methods to manipulate properties that can be accessed by outsiders. It’s like we can’t see the internal parts (attributes) of the air conditioner hanging on the wall, but we can control the air conditioner by remote control. If properties do not want to be accessed by outsiders, we do not need to provide methods to access them. But if a class has no methods to access from the outside world, then that class is meaningless. If we don’t have the air conditioner remote control, then we can’t control the air conditioning refrigeration, and the air conditioning itself is meaningless (there are many other methods, but this is just for example).

public class Student { private int id; Private String name; Public int getId() {return id; } public void setId(int id) {this.id = id; } public String getName() {return name; } public void setName(String name) {this.name = name; }}Copy the code

1.2.2. Inheritance

Objects of different types often have a certain amount in common with each other. For example, Xiao Ming, Xiao Hong and Xiao Li all share student characteristics (class, student number, etc.). At the same time, each object defines additional features that make them unique. For example, Xiao Ming is good at math, and Xiao Hong has a charming personality. Xiao Li has more strength. Inheritance is the technique of using the definition of an existing class as a basis to create a new class. The definition of a new class can add new data or new functions, or use the functions of the parent class, but can not selectively inherit the parent class. Through the use of inheritance, we can quickly create new classes, can improve the reuse of code, program maintainability, save a lot of time to create new classes, improve our development efficiency.

Here are three things to remember about inheritance:

1, a subclass owns all the attributes and methods of the parent object (including private attributes and methods), but the private attributes and methods of the parent object are not accessible to the subclass.

2. Subclasses can have their own attributes and methods, that is, subclasses can extend their parent classes. 3. Subclasses can implement methods of their parent class in their own way. (More on that later).

1.2.3. Polymorphism

Polymorphism, as the name suggests, means that an object has more than one state. A reference to a parent class refers to an instance of a child class.

Characteristics of polymorphism:

1. There is an inheritance (class)/implementation (interface) relationship between object type and reference type;

2. Which class method is invoked by a method that refers to a type variable must be determined during program execution.

3. Polymorphism cannot call methods that exist only in subclasses but not in superclasses.

4. If a subclass overrides a method of its parent class, it actually executes the method overridden by the subclass. If the subclass does not override a method of its parent class, it executes the method of its parent class.

1.3. The modifier

1.3.1. Why is it illegal to call a non-static member within a static method?

Because static methods can be called without an object, other non-static variables cannot be called in a static method, nor can members of a non-static variable be accessed.

1.3.2. What is the difference between static and instance methods

When static methods are called externally, the “class name” can be used. Method name, or object name. Method name “. Instance methods have only the latter. That is, you can call a static method without creating an object.

2, static methods only allow access to static members (i.e., static member variables and static methods), but do not allow access to instance member variables and instance methods; Instance methods do not have this limitation.

1.5. Other important knowledge points

1.5.1. String What is the difference between StringBuffer and StringBuilder? Why is String immutable?

In simple terms: The String class uses the final keyword to modify character arrays to hold strings, and the private final char value[], so strings are immutable.

Add (from Issue 675) : After Java 9, the implementation of the String class changed to a byte array to store strings private final byte[] value;

AbstractStringBuilder and StringBuffer both inherit from AbstractStringBuilder classes, AbstractStringBuilder also uses character arrays to hold the string char[]value without the final keyword, so both objects are mutable.

AbstractStringBuilder constructor AbstractStringBuilder constructor AbstractStringBuilder constructor AbstractStringBuilder constructor

AbstractStringBuilder.java

abstract class AbstractStringBuilder implements Appendable, CharSequence {
    /**
     * The value is used for character storage.
     */
    char[] value;

    /**
     * The count is the number of characters used.
     */
    int count;

    AbstractStringBuilder(int capacity) {
        value = new char[capacity];
    }}
Copy the code

Thread safety

Objects in strings are immutable, which means they are considered constants, thread-safe. AbstractStringBuilder AbstractStringBuilder is a common parent of StringBuilder and StringBuffer. AbstractStringBuilder defines some basic string operations, such as expandCapacity, Append, insert, indexOf and other public methods. StringBuffer places synchronization locks on methods or on invoked methods, so it is thread-safe. StringBuilder does not lock methods synchronously-so it is not thread-safe.

performance

Each time a String type is changed, a new String is generated and a pointer is pointed to the new String. A StringBuffer operates on the StringBuffer object itself each time, rather than generating new objects and changing object references. Using StringBuilder in the same situation yields only 10% to 15% performance improvement over using StringBuffer, but at the risk of multithreading insecurity.

Summary of the use of the three:

1, Operating on a small amount of data: For String 2, single-threaded operating on a large amount of data in the String buffer: for StringBuilder 3, multi-threaded operating on a large amount of data in the String buffer: for StringBuffer

1.5.2. Summary of common methods of Object class

The Object class is a special class that is the parent of all classes. It mainly provides the following 11 methods:

public final native Class<? > getClass()//native method, used to return the Class object of the current runtime object, using the final keyword, so subclass overrides are not allowed. Public native int hashCode() // the native method used to return the hashCode of an object, mainly used in hash tables, such as the JDK HashMap. Public Boolean equals(Object obj)// Used to compare the memory addresses of two objects. The String class overridden this method. Protected native Object clone () throws CloneNotSupportedException / / naitive method, is used to create and return a copy of the current Object. In general, for any object x, the expression x.lone ()! = x is true, x.lone ().getClass() == x.gottclass () is true. Object does not implement the Cloneable interface, so don't rewrite the clone method and call CloneNotSupportedException abnormal happens. Public String toString()// Returns the name of the class @ the hexadecimal String of the instance's hash code. It is recommended that all subclasses of Object override this method. Public final native void notify()// Native method, and cannot be overridden. Wakes up a thread waiting on the monitor of this object (the monitor is equivalent to a lock). If there are multiple threads waiting, only one will wake up randomly. Public final native void notifyAll()// Native method, and cannot be overridden. As with Notify, the only difference is that all threads waiting on this object's monitor are woken up instead of one thread. Public final native void wait (long timeout) throws InterruptedException / / native methods, and cannot be rewritten. Suspends the execution of the thread. Note that the sleep method does not release the lock, while the wait method does. Timeout is the wait time. Public final void Wait (long timeout, int nanos) throws InterruptedException// Additional nanos parameter. This parameter specifies the additional time (in nanoseconds and ranges from 0 to 999999).  So you have to add nanos milliseconds to the timeout. Public final void wait() throws InterruptedException// Same as the other two wait methods, Protected void Finalize () throws Throwable {}// The operation triggered when the instance is collected by the garbage collectorCopy the code

1.5.3. == equals(Important)

== : This is used to determine whether the addresses of two objects are equal. That is, determine whether two objects are the same object (basic data type)

Compare values, reference data types

Compare memory addresses).

Equals () : Also checks whether two objects are equal. But it is generally used in two ways:

Case 1: The class does not override equals(). Comparing two objects of that class through equals() is equivalent to comparing them through “==”. Case 2: The class overrides equals(). In general, we override the equals() method to compare the contents of two objects; Return true if their contents are equal (that is, the objects are considered equal).

Here’s an example:

public class test1 { public static void main(String[] args) { String a = new String("ab"); // a is a reference to String b = new String("ab"); // b is another reference to the same object as String aa = "ab"; String bb = "ab"; If (aa ==bb) // true system.out.println ("aa==bb"); If (a ==b) // false, not the same object system.out.println ("a==b"); if (a.equals(b)) // true System.out.println("aEQb"); If (42 == 42.0) {// true system.out.println ("true"); }}}Copy the code

Description:

1. The equals method of String is overridden, because the equals method of object compares the memory addresses of objects, while the equals method of String compares the values of objects.

2. When creating an object of type String, the virtual machine looks in the constant pool for an existing object with the same value as the object to be created, and assigns it to the current reference. If not, create a new String in the constant pool.

1.5.4. HashCode and Equals (Important)

The interviewer may ask you, “Have you overridden hashcode and equals? Why do you have to override hashCode to override equals?”

2.5.4.1. HashCode () Introduction

HashCode () is used to get a hashCode, also known as a hashCode; It actually returns an int. The purpose of this hash code is to determine the index position of the object in the hash table. HashCode () is defined in the JDK’s Object.java, which means that any class in Java contains a hashCode() function.

Hash table stores key-value pairs. It can quickly retrieve the corresponding value according to the key. That’s where the hash code comes in! (Can quickly find the desired object)

2.5.4.2. Why hashCode

Let’s start with “how does a HashSet check for duplicates” as an example of why hashCode is needed: When you add an object to a HashSet, the HashSet evaluates the object’s Hashcode value to determine where the object was added to. It also compares the hashcode value of other objects at that location. If there is no matching Hashcode, A HashSet assumes that the object is not repeated. But if objects with the same Hashcode value are found, the equals() method is called to check whether objects with hashCode equality are really the same. If they are the same, the HashSet will not let the join succeed. If it is different, it will be rehashed to another location. (From the second edition of my Java primer, Head First Java). This significantly reduced the number of equals calls, which in turn significantly increased the execution speed.

HashCode () is used to retrieve hash codes. It actually returns an int. The purpose of this hash code is to determine the index position of the object in the hash table. HashCode () is useful in hash tables, not in other cases. The purpose of hashCode() in a hash table is to get the hashCode of an object and thereby determine its position in the hash table.

2.5.4.3. HashCode () and equals ()

Two objects are equal. Calling equals on both objects returns true 3. Two objects have the same hashcode value, and they don’t have to be equal either. The hashCode method must also be overridden 5. The default behavior of hashCode() is to generate unique values for objects on the heap. If hashCode() is not overridden, the two objects of the class will never be equal anyway (even if they point to the same data)

2.5.5. What if some fields in Java serialization do not want to be serialized?

For variables that do not want to be serialized, use the TRANSIENT keyword modifier.

The transient keyword prevents serialization of variables in an instance that are modified with this keyword. When an object is deserialized, variable values modified transient are not persisted and restored. Transient can only modify variables, not classes and methods.

2.5.6. Get two common methods of keyboard input

Method 1: Use Scanner

Scanner input = new Scanner(System.in);
String s  = input.nextLine();
input.close();
Copy the code

Method 2: Through BufferedReader

BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String s = input.readLine();
Copy the code

Java internal training, recommended me: Java learning exchange group.