A 100 day sprint for the interview of a Java factory - accumulated over time, three questions per day [Day5] - Basic Part 2

daysprintinterviewjavafactory

Hello everyone , I'm Chen ha ha , Five years in the North . My friends who know me know , I come from a non-technical background , become a monk or nun late in life , Universities are bad too ! This kind of background drifts North , You don't even know what you're going through ???.

beg to differ , I'm sure you're like me , They all have a big factory dream , As a senior Java player , Know the importance of interview , Next I'm going to use 100 Days time , be based on Java High frequency interview questions in job interview , With everyday 3 topic In the form of , Take you through the hot interview questions and the appropriate answers . Of course , I won't go too far , Because I'm afraid I can't remember !!

therefore , I hope you can add some doubts in the comments section 、 Opinions and strange questions in the interview , I hope this 100 The sky can let us have the quality to fly over , Rush into the big factory together !!, Let's learn together (juan) get up !!!

 Insert picture description here

Enjoy it since we SQL Thigh group The brick moving site of my classmates , coordinate : Qingdao .


ticket


This column Java Development post high frequency interview questions are mainly from the following technology stack :Java Basic knowledge of Assembly containers Concurrent programming JVMSpring Family bucket MyBatis etc. ORMapping frame MySQL database Redis cache RabbitMQ Message queue Linux Operation skills etc. .

Interview questions 1: Let's talk about the differences between abstract classes and interfaces ?

Serious answer :

The main difference between abstract classes and interfaces :

In terms of design , An abstract class is an abstraction of a class , Is a template design ; Interface is the abstraction of behavior , It's a code of conduct .

  • A class can have multiple interfaces Only one parent class can be inherited
  • Abstract classes can have constructors , Cannot have constructor in interface .
  • Abstract classes can have common member variables , There are no normal member variables in the interface
  • All methods in the interface must be abstract Of ; Abstract classes can have implemented methods
  • The access type of an abstract method in an abstract class can be public,protected; But an abstract method in an interface can only be public Type of , And the default is public abstract type
  • Static methods can be included in abstract classes , Static methods cannot be included in an interface
  • Static member variables can be included in both abstract classes and interfaces , The access type of static member variable in abstract class can be arbitrary ; But the variables defined in the interface can only be public static final type , And the default is public static final type .

Java8 The default method and static method are introduced into the interface of , To reduce the difference between abstract classes and interfaces .

Interfaces and abstract classes have their own advantages and disadvantages , In the choice of interfaces and abstract classes , Such a principle must be observed :

  • Behavior models should always be defined through interfaces rather than abstract classes , So the interface is usually preferred , Try to use as few abstract classes as possible .
  • When choosing an abstract class, it's usually the following : You need to define the behavior of subclasses , It also provides common functions for subclasses .

In depth inquiry :

Questioning 1: Tell me about your understanding of abstract classes , What the hell is he for

We often say that the core idea of object-oriented is : Abstract first , Post specific . Abstract classes are classes that contain abstract methods , Can't be instantiated , Abstract classes are often used as template classes .

Interfaces play a more important role in system architecture design methods , It is mainly used to define the communication contract between modules .

And abstract classes play a role in code implementation , Can achieve code reuse , for example , Template method design pattern is a typical application of abstract class , Suppose that all of the Servlet All classes need to use the same way to judge permissions 、 Record access logs and handle exceptions , Then you can define an abstract base class , Let all Servlet All inherit this abstract base class , In the abstract base class service Method 、 Record access logs and code to handle exceptions , In each subclass, it just completes its own business logic code . Some code in the middle of the parent method is not sure , Leave it to subclasses , Just use the template method to design patterns .

Questioning 2: Implementing an interface with abstract classes , What's the difference between implementing an interface with a normal class ?

Generally speaking, we use ordinary classes to implement interfaces , This ordinary class must implement all the methods in the interface , The result is that you need to implement redundant methods in ordinary classes , Causes code redundancy . But if we use abstract classes to implement interfaces , Then you can only implement some of the methods in the interface , And when other classes inherit this abstract class , You can still implement methods that exist in the interface but are not implemented by abstract classes .

As the following code , Abstract classes just implement interfaces A The method in a, Method b, But when the class C Inherited abstract class B when , Interface can be implemented directly A Medium c Method , One thing to note is that , class C The method in a, Method b Are the calling parent classes B Methods a, Method b, It's not a direct way to implement the interface a and b.

/**
* Interface
*/
interface A{
public void aaa();
public void bbb();
public void ccc();
}
/**
* abstract class
*/
abstract class B implements A{
public void aaa(){}
public void bbb(){}
}
/**
* Implementation class
*/
public class C extends B{
public void aaa(){}
public void bbb(){}
public void ccc(){}
}

Questioning 3: Abstract classes can be used final Embellishment ?

You can't , Defining an abstract class is about having other classes inherit from it , If defined as final This class cannot be inherited , So there's going to be conflict , therefore final You cannot modify an abstract class .

 Insert picture description here


 Insert picture description here

break , Enjoy it since we SQL Thigh group The brick moving site of beautiful students , coordinate : Xi'an .


Interview questions 2:final stay Java What's in it ?

Serious answer :

Used to decorate a class 、 Methods and properties ;

1、 decorator

When used final When modifying a class , Indicates that the class cannot be inherited by other classes . It should be noted that :final All member methods in a class are implicitly defined as final Method .

2、 Modification methods

Use final The main reason is to lock the method , To prevent inheritance classes from changing or overriding it .

If in the parent class final The access rights of the method are private, This will result in the subclass not inheriting the method directly , therefore , In this case, functions with the same method name can be defined in the subclass , This is not the case with rewriting final The contradiction of , Instead, it redefines new methods in subclasses .

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(); // Log output :getName - B
}
}

3、 Modifying variables

When final When modifying a basic data type , Indicates that the value of the basic data type cannot change once it is initialized ; If final When modifying a reference type , After it is initialized, it can no longer point to other objects , But the content of the object that the reference refers to can change . It's one thing in essence , Because the value of the reference is an address ,final Required value , That is, the value of the address does not change .

final Modify a member variable ( attribute ), Initialization must be displayed . There are two initialization methods , One is to initialize when a variable is declared ; The second method is to declare a variable without assigning an initial value , However, the initial value should be assigned to the variable in all constructors of the class in which the variable is located .

When the parameter type of a function is declared as final when , Indicates that the parameter is read-only . That is, you can read and use this parameter , However, the value of this parameter cannot be changed .

In depth inquiry :

Questioning 1: Can you tell me something about it final、finally、finalize The difference? ?

  • final Modifiable class 、 Variable 、 Method , A modifier class means that it cannot be inherited 、 A modifier means that the method cannot be overridden 、 Modifier variable means that the variable is a constant and cannot be reassigned .
  • finally The general effect is try-catch Block of code , When handling exceptions , Usually we will have to execute code methods finally Block of code , Indicates whether or not an exception has occurred , This code block will execute , It is usually used to store some code for closing resources . Of course , There are many other situations that can't go finally~
  • finalize It's a method , Belong to Object class , and Object Class is the parent of all classes , This method is generally called by the garbage collector , When we call System.gc() Method time , Called by garbage collector finalize(), Recycling waste , The final judgment of whether an object is recyclable .

 Insert picture description here

break , Enjoy it since we SQL Thigh group The brick moving site of my classmates , coordinate : Beijing .

North drifters, guess where it is ?


Interview questions 3: You are right about Java Do you understand ?

Serious answer :

Serialization process :

It means to put a Java Object becomes binary content , In essence, it is a byte[] Array .

Because after serialization, you can put byte[] Save to file , Or the byte[] Over the Internet to remote (IO), such , It's equivalent to putting Java Objects are stored in files or transmitted over the network .

Deserialization process :

Put a binary content ( That is to say byte[] Array ) Change back Java object . With deserialization , Save to a file byte[] Arrays can be “ Change back ”Java object , Or read it from the Internet byte[] And put it “ Change back ”Java object .

Here are some examples of using serialization :

  • A file that stores data on disk in an object-oriented manner , for example ,Redis Storage Student List of objects .
  • Save the state of the program on disk , for example , Save game state .
  • Send data as form objects over the web , for example , Sending messages as objects in a chat application .

One Java Objects should be serializable , A special java.io.Serializable Interface , It is defined as follows :

public interface Serializable {
}

Serializable The interface does not define any methods , It's an empty interface . We call such an empty interface “ Tag interface ”(Marker Interface), A class that implements a tag interface simply pastes itself with a “ Mark ”, It doesn't add any methods .

In depth inquiry :

Questioning 1:Java How serialization works ?

If and only if the class of an object implements java.io.Serializable Interface , This object is eligible for serialization . Serializable Is a tag interface ( There's no way ), The interface tells Java virtual machine (JVM) Objects of this class are ready to be written to persistent storage or read over the network .

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

  • ObjectOutputStream.writeObject(Object): take Serializable Write to the output stream . If some of the objects to be serialized are not implemented Serializable Interface , This method will trigger NotSerializableException.

  • ObjectInputStream.readObject(): Read... From the input stream , Construct and return an object . If you can't find the class of the serialized object , This method will trigger ClassNotFoundException.

If there is a problem with the class used by serialization , Then both methods will trigger InvalidClassException, In case of I / O error , Will trigger IOException. No matter what NotSerializableException and InvalidClassException Subclass IOException abnormal .

Let's take a simple example . The following code will String The object is serialized with the name “ data.ser” The file of . String objects are serializable , because 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 file “ data.ser” Medium String object :

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);
}

Please note that ,readObject() Return to one Object Object of type , So you need to cast it to a serializable class , In this case String class .

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

Given the following class :

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 code above , You'll find two things :

  • long serialVersionUID Constant of type .

  • Member variables age Marked as transient.

    Here are two questions for us to understand .

Questioning 2: What is? serialVersionUID constant

serialVersionUID It's a constant , The version used to uniquely identify the serializable class . When constructing an object from an input stream ,JVM Check this constant during deserialization . If the object being read is serialVersionUID Different from the sequence number specified in the class , be JVM Throw out InvalidClassException. This is to ensure that the object being constructed is the same as serialVersionUID Class compatibility of .

Please note that ,serialVersionUID It's optional . This means that if you don't explicitly state Java compiler , It will generate a .

that , Why explicitly declare serialVersionUID Well ?

as a result of : Automatically generated serialVersionUID It's a class based element ( Member variables , Method , Constructors, etc ) Calculated . If one of these elements changes ,serialVersionUID Will also change . Imagine this :

  1. You write a program , take Student Class is stored in a file .Student Class is not explicitly declared serialVersionUID.
  2. Sometimes , You have updated Student class ( for example , Added a new private method ), Now automatically generated serialVersionUID It has also been changed .
  3. Your program cannot deserialize a previously written Student object , Because of the serialVersionUID Different .JVM Throw out InvalidClassException.

This is why it is recommended to explicitly add serialVersionUID Why .

Questioning 3、 Do you know what instantaneous variables are ?

Above Student Class , You see the member variable age Marked as transient, Am I right? ?JVM Skip transient variables during serialization . This means that when you serialize an object, you don't store age The value of the variable .

therefore , If member variables don't need to be serialized , It can be marked as transient .

The following code will Student The object is serialized with the name “ students.ser” The file of :

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);
}

Please note that , Before serializing objects , Variable age The value of is 22.

The following code deserializes from the file Student object :

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 individual
123 - John - 0

Daily summary

Today we reviewed the common questions in the interview JAVA The three problems of the basic part , Do you have a good idea ? by the way , If your friend is also preparing for the interview , Please throw this series to him , If he takes it seriously , I'm sure I'll thank you !! Okay , That's it today , Students who have lost their studies , Remember to leave a message in the comment area : Clock in ., To inspire the students .

copyright:author[m0_ fifty-four million eight hundred and fifty thousand four hu],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/175/202206240016332183.html