Java Gang Dachang Interview Hundred Days Sprint-Accumulate every day, three questions a day [Day5]-Basics 2

Hello everyone, I am Chen Haha, and I have been drifting north for five years. Friends who know me know that I was born in a non-major class, renounced halfway through, and the university is also very poor! Coming to Beidiao with this background, you don’t know what you will experience 🙃🙃.

I can’t agree. I believe everyone is like me 都有一个大厂梦. As a senior Java player, I know the importance of interviews. Next, I’m going to spend 100 days, based on the high-frequency interview questions in Java post interviews, 每日3题and take you in the form of Go through the popular interview questions and the appropriate answers. Of course, I won't go too deep, because I'm afraid I can't remember! !

因此,不足的地方希望各位在评论区补充疑惑、见解以及面试中遇到的奇葩问法, I hope these 100 days will allow us to fly over qualitatively and rush into the big factory together! ! , Let us learn together (juan)! ! !
Insert picture description here

Appreciate the SQL大腿群brick-moving site from our classmates, coordinate: Qingdao.


ticket


This column Java developers Kong high-frequency face questions from each of the following major technology Java基础知识stack: 集合容器, 并发编程, JVM, Spring全家桶, MyBatis等ORMapping框架, MySQL数据库, Redis缓存, RabbitMQ消息队列, , Linux操作技巧and so on.

Interview question 1: What are the differences between abstract classes and interfaces?

Seriously answer:

The main difference between abstract class and interface:

From a design perspective, an abstract class is an abstraction of a class and a template design; an interface is an abstraction of behavior and a norm of behavior.

  • A class can have multiple interfaces and can only inherit from one parent class
  • Abstract classes can have constructors, but interfaces cannot have constructors.
  • There can be ordinary member variables in the abstract class, but there are no ordinary member variables in the interface
  • All methods in the interface must be abstract; abstract classes can have implemented methods
  • The access type of the abstract method in the abstract class can be public, protected; but the abstract method in the interface can only be of the public type, and the default is the public abstract type
  • Static methods can be contained in abstract classes, and static methods cannot be contained in interfaces
  • Both abstract classes and interfaces can contain static member variables, and the access type of static member variables in the abstract class can be arbitrary; but the variables defined in the interface can only be of public static final type, and the default is public static final type.

Java8中接口中引入默认方法和静态方法,以此来减少抽象类和接口之间的差异。

Interfaces and abstract classes have their own advantages and disadvantages. In the selection of interfaces and abstract classes, you must abide by this principle:
  • Behavioral models should always be defined through interfaces rather than abstract classes, so interfaces are usually preferred and abstract classes are used as little as possible.
  • When choosing an abstract class, it is usually the following situation: you need to define the behavior of the subclass, and provide common functions for the subclass.

In-depth inquiry:

Follow-up 1: Tell me about your understanding of abstract classes. What is it for?

我们常说面向对象的核心思想是:先抽象,后具体。Abstract classes are classes that contain abstract methods and cannot be instantiated. Abstract classes are often used as template classes.

Interfaces play a role more in the system architecture design method, mainly used to define communication contracts between modules.

Abstract classes play a role in code implementation and can realize code reuse. For example, the template method design pattern is a typical application of abstract classes. It is assumed that all Servlet classes of a project must use the same method for authority judgment and record access. Log and handle exceptions, then you can define an abstract base class, so that all Servlets inherit this abstract base class, in the service method of the abstract base class to complete the authority judgment, record the access log and handle exception code, in each sub Only complete the respective business logic code in the class.父类方法中间的某段代码不确定,再留给子类干,就用模板方法设计模式。

Follow-up 2: Is there any difference between implementing an interface with an abstract class and implementing an interface with an ordinary class?

Generally speaking, we use ordinary classes to implement interfaces. This ordinary class must implement all the methods in the interface. As a result, redundant methods need to be implemented in ordinary classes, causing code redundancy. But if we use an abstract class to implement an interface, then we can only implement some of the methods in the interface, and when other classes inherit this abstract class, they can still implement methods in the interface that are not implemented by the abstract class.

As in the following code, the abstract class only implements method a and method b in interface A, but when class C inherits abstract class B, it can directly implement method c in interface A. One thing to note is that in class C Method a and method b are both methods a and b of the parent class B that are called, which are not methods a and b that directly implement the interface.

/**
 *接口
 */
 interface A{
 public void aaa();
 public void bbb();
 public void ccc();
 }
 /**
 *抽象类
 */
 abstract class B implements A{
 public void aaa(){}
 public void bbb(){}
 }
 /**
 * 实现类
 */
 public class C extends B{
 public void aaa(){}
 public void bbb(){}
 public void ccc(){}
 }

Follow-up 3: Can abstract classes use final modification?

No, the definition of an abstract class is for other classes to inherit. If it is defined as final, the class cannot be inherited, which will cause conflicts with each other, so final cannot modify the abstract class.

Insert picture description here

Insert picture description here

Take a break between classes and admire the SQL大腿群brick-moving site from our beautiful classmates. Coordinate: Xi'an.


Interview question 2: What is the role of final in Java?

Seriously answer:

Used to modify classes, methods and attributes;

1. Modification

When a class is modified with final, it indicates that the class cannot be inherited by other classes. have to be aware of is:final类中所有的成员方法都会隐式的定义为final方法。

2. Modification method

The main reason for using the final method is to lock the method to prevent the inherited class from changing or rewriting it.

If the access permission of the final method in the parent class is private, the method cannot be directly inherited in the subclass. Therefore, at this time, a function with the same method name can be defined in the subclass. This will not conflict with overriding final. Instead, the new method is redefined in the subclass.

class A{
    private final void getName(){
        System.out.println("getName - A");
    }
}

public class B extends A{
    public void getName(){
        System.out.println("getName - B");
    }

    public void main(String[]args){
        this.getName(); // 日志输出:getName - B
    }
}

3. Modified variables

When final modifies a basic data type, it means that the value of the basic data type cannot change after initialization; if final modifies a reference type, it can no longer point to other objects after its initialization, but The content of the object pointed to by the reference can change. It is essentially the same thing, because the referenced value is an address, and final requires a value, that is, the value of the address does not change.

Final modifies a member variable (attribute), which must be displayed and initialized. There are two initialization methods, one is to initialize when the variable is declared; the second method is to not assign an initial value when declaring the variable, but to assign this variable in all the constructors of the class where the variable is located Initial value.

When the parameter type of the function is declared as final, it means that the parameter is read-only. That is, you can read and use the parameter, but you cannot change the value of the parameter.

In-depth inquiry:

Follow-up 1: Can you tell me the difference between final, finally, and finalize separately?

  • Final can modify classes, variables, and methods. Modified classes indicate that the class cannot be inherited, modified methods indicate that the method cannot be overridden, and modified variables indicate that the variable is a constant and cannot be reassigned.
  • Finally is generally used in the try-catch code block. When dealing with exceptions, we usually must execute the code method in the finally code block, which means that the code block will be executed regardless of whether there is an exception or not, and it is generally used to store some closed resources. Code. of course,还有多种情况走不了finally~
  • Finalize is a method, a method of the Object class, and the Object class is the parent class of all classes. This method is generally called by the garbage collector. When we call the System.gc() method, the garbage collector calls finalize (), garbage collection, the final judgment of whether an object is recyclable.

Insert picture description here

Take a break between classes and enjoy the SQL大腿群brick-moving site from our classmates. Coordinate: Beijing.

Guess what the location is?


Interview Question 3: Do you know Java serialization?

Seriously answer:

Serialization process:

Refers to turning a Java object into binary content, which is essentially a byte[] array.

Because after serialization, byte[] can be saved to a file, or byte[] can be transmitted to remote (IO) through the network, so that it is equivalent to storing the Java object in a file or transmitting it through the network.

Deserialization process:

Convert a binary content (that is, byte[] array) back to a Java object. With deserialization, the byte[] array saved in the file can be "changed back" to a Java object, or byte[] can be read from the network and "changed back" to a Java object.

Here are some examples of using serialization:
  • Store data to a file on disk in an object-oriented manner. For example, Redis stores a list of Student objects.
  • Save the state of the program on the disk, for example, save the state of the game.
  • Send data as form objects over the network, for example, send messages as objects in a chat application.

For a Java object to be serializable, it must implement a special one java.io.Serializable接口, which is defined as follows:

public interface Serializable {
}

The Serializable interface does not define any methods, it is an empty interface. We call such an empty interface “标记接口”(Marker Interface), the class that implements the marked interface just puts a "mark" on itself, and does not add any methods.

In-depth inquiry:

Follow-up 1: How does Java serialization work?

java.io.SerializableThe object is eligible for serialization if and only if its class implements the interface. Serializable is a marked interface (without any methods) that tells the Java Virtual Machine (JVM) that objects of this class are ready to be written to persistent storage or read through the network.

By default, the JVM is responsible for the process of writing and reading serializable objects. The serialization/deserialization function is exposed through the following two methods of the object stream class:

ObjectOutputStream。writeObject(Object): 可序列化Write the object to the output stream. If some objects to be serialized do not implement the Serializable interface, this method will be raised NotSerializableException.

ObjectInputStream。readObject(): Read from the input stream, construct and return an object. If the class of the serialized object cannot be found, this method will be raised ClassNotFoundException.

If there is a problem with the class used for serialization, both methods will be raised InvalidClassException, and if an I/O error occurs, it will be raised IOException. Regardless of whether the NotSerializableExceptionsum InvalidClassExceptionis a subclass IOExceptionexception.

Let us look at a simple example. The following code serializes the String object into a file named "data.ser". String objects are serializable because the String class implements the Serializable interface:

 
String filePath = "data.ser";
String message = "Java Serialization is Cool";
 
try (
    FileOutputStream fos = new FileOutputStream(filePath);
    ObjectOutputStream outputStream = new ObjectOutputStream(fos);
) {
 
    outputStream.writeObject(message);
 
} catch (IOException ex) {
    System.err.println(ex);
}
 

The following code deserializes the String object in the file "data.ser":

String filePath = "data.ser";
 
try (
    FileInputStream fis = new FileInputStream(filePath);
    ObjectInputStream inputStream = new ObjectInputStream(fis);
) {
 
    String message = (String) inputStream.readObject();
 
    System.out.println("Message: " + message);
 
} catch (ClassNotFoundException ex) {
    System.err.println("Class not found: " + ex);
} catch (IOException ex) {
    System.err.println("IO error: " + ex);
}

Note that readObject() returns an object of type Object, so you need to cast it to a serializable class, in this case the String class.

Let's look at a more complex example involving the use of custom classes.

Given the following student classes :

import java.io.*;
import java.util.*;
 
/**
 * Student.java
 * @author chenhh
 */
public class Student extends Person implements Serializable {
    public static final long serialVersionUID = 1234L;
 
    private long studentId;
    private String name;
    private transient int age;
 
    public Student(long studentId, String name, int age) {
        super();
        this.studentId = studentId;
        this.name = name;
        this.age = age;
 
        System.out.println("Constructor");
    }
 
    public String toString() {
        return String.format("%d - %s - %d", studentId, name, age);
    }
}

Like the above code, you will find two points:

  • A constant of type long serialVersionUID.
  • The member variable age is marked as transient.

    The following two questions let us understand them.

Follow-up 2: What is the serialVersionUID constant

serialVersionUIDIs a constant used to uniquely identify the version of the serializable class. When constructing an object from the input stream, the JVM checks this constant during the deserialization process. If serialVersionUIDthe serial number of the object being read is different from the serial number specified in the class, the JVM throws InvalidClassException. This is to ensure that the object being constructed is serialVersionUIDcompatible with the same class.

Please note that it serialVersionUIDis optional. This means that if you don't explicitly declare the Java compiler, it will generate one.

So, why do you want to declare serialVersionUIDit explicitly ?

The reason is: the automatically generated serialVersionUIDcalculations are based on the elements of the class (member variables, methods, constructors, etc.). If one of these elements changes, serialVersionUIDit will also change. Imagine this situation:

  1. You have written a program to store some objects of the Student class in a file. The Student class has no serialVersionUID explicitly declared.
  2. Sometimes, you update the Student class (for example, add a new private method), and now the automatically generated serialVersionUID is also changed.
  3. Your program cannot deserialize the Student object written earlier because the serialVersionUID there is different. JVM throws InvalidClassException.

This is why it is recommended to explicitly add serialVersionUID to serializable classes.

Follow-up 3. Then do you know what an instantaneous variable is?

In the Student class above, you see that the member variable age is marked as transient, right? JVM skips transient variables during serialization. This means that the value of the age variable is not stored when the object is serialized.

Therefore, if the member variable does not need to be serialized, it can be marked as transient.

The following code serializes the Student object into a file named "students.ser":

String filePath = "students.ser";
Student student = new Student(123, "John", 22);
 
try (
    FileOutputStream fos = new FileOutputStream(filePath);
    ObjectOutputStream outputStream = new ObjectOutputStream(fos);
) {
 
    outputStream.writeObject(student);
 
} catch (IOException ex) {
    System.err.println(ex);
}

Note that before serializing the object, the value of the variable age is 22.

The following code deserializes the Student object from the file:

String filePath = "students.ser";
 
try (
    FileInputStream fis = new FileInputStream(filePath);
    ObjectInputStream inputStream = new ObjectInputStream(fis);
) {
 
    Student student = (Student) inputStream.readObject();
 
    System.out.println(student);
 
} catch (ClassNotFoundException ex) {
    System.err.println("Class not found: " + ex);
} catch (IOException ex) {
    System.err.println("IO error: " + ex);
}

This code will output the following output:

1
123-John-0

Daily summary

Today we reviewed the three questions in the basic part of JAVA that are often tested in the interview. Have you done it well? 对了,如果你的朋友也在准备面试,请将这个系列扔给他,如果他认真对待,肯定会感谢你的!!Okay, let’s stop here today 记得在评论区留言:打卡。, to encourage students who have lost their studies .