[golden three silver four sides trial season] Java object-oriented high-frequency interview questions

  the golden three silver four is a good time for job hopping and salary increase. BOGO has sorted out a lot of high-frequency interview questions to help you find a better job. Oh, pay attention and thank you for your support.

Object oriented interview questions

1. Talk about your understanding of object-oriented thinking?

Process oriented programming (POP): it is a process centered programming idea

Object oriented programming (OOP): compared with process oriented programming, object-oriented method organizes relevant data and methods into a whole, carries out system modeling from a higher level, and is closer to the natural operation mode of things

2. Talk about your understanding of object-oriented characteristics

encapsulation

That is, the properties and methods of the object are wrapped up and can only be accessed through the agreed interface

Encapsulation is a kind of information hiding technology, which is realized by keyword private in java.

package com.bobo.interview0001.domain;

/**
 * Attribute + method
 */
public class User {
    // Set age to private property
    private int age;

    public String name;

    /**
     * Provides a method for setting the age attribute to the outside world
     * @param age
     */
    public void setAge(int age){
        if(age < 0 || age > 120){
            System.out.println("age The setting of is illegal!!!");
            age = 0;
        }
        this.age = age;
    }

    /**
     * Provides a method for the outside world to obtain the age attribute
     * @return
     */
    public int getAge(){
        return age;
    }


}

   advantages of encapsulation: it can separate private data from public data, protect private data and improve the security of the program!!!

inherit

  inheritance is the most prominent feature of object-oriented. Inheritance is to derive a new class from an existing class. The new class can absorb the data properties and behaviors of the existing class and expand new capabilities.
Why inherit

  1. Real relationship reflecting reality

  2. Reduce code redundancy

  3. Extend and override the properties and methods of the parent class

   in inheritance, subclasses can not selectively inherit the things of the parent class, but all inherit the properties and methods of the parent class. The parent class is also called super class or base class, and the child class is also called derived class. A parent class is a generalization of a subclass, and a subclass is a specialization (concretization) of a parent class. Multiple inheritance is not supported in java. A class can only have one parent class at most. In java, multi inheritance is implemented through interfaces.

public class Person {
    private String userName;
    private int age;

    private String sex;
    private String address;
    private String idCard;

    public void show(){
        System.out.println("Method in parent class");
    }
}
public class Doctor extends Person{
    @Override
    public void show() {
        System.out.println("Doctor ... show");
    }
}
public class Student  extends Person{
    private String ClassNum;
    private String stuNo;
    // ....
    public void learn(){

    }

    @Override
    public void show() {
        System.out.println("Student ... show");
    }
}

polymorphic

   multiple states and polymorphisms of Java objects are mainly based on Inheritance and rewriting. Finally, the same type can be realized and the same method can be called with different results

    public static void main(String[] args) {
        // Embodiment of polymorphism
        Person p1 = new Student();
        p1.show();
        Person p2 = new Doctor();
        p2.show();
    }

3. Introduce the following access modifier

Modifier Current classSame packageSubclassOther packages
public
protected×
default××
private×××

   pay attention to protected and default. Compared with protected, default has one more difference. The subclasses under the package are visible

4. Is string a basic data type?

There are eight basic data types in Java:

  • byte
  • short
  • int
  • long
  • float
  • double
  • char
  • boolean

   string type is obviously not among the eight basic data types. String type is the reference type we talk about

5. Is float f = 6.6 correct?

   incorrect. 6.6 defaults to double precision type. Assigning double type to float type and transforming the attribute downward will cause precision loss

public class Demo01 {

    public static void main(String[] args) {
        // Decimals are double by default, and double precision types are transformed downward. Precision is lost
        float f2 = 1.1;
        float f = 6.6F;
        float f1 = 7.7F;
    }
}

6 procedure question 1

short s1 = 1; 
s1 = s1 + 1; // Cast is required here

Is there anything wrong Wrong

short s1 = 1; 
s1 += 1; // s1 = (short) ( s1 + 1 )

Is there a mistake-- No mistake

7. Procedural question 2

The output of the following program is:

    public static void main(String[] args) {
        Integer f1=100,f2=100,f3=150,f4=150;
        System.out.println(f1==f2);
        System.out.println(f3==f4);
    }

Output results: true, false

Explanation of reasons:

Definitions in IntegerCache

    private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[];

        static {
            // high value may be configured by property
            int h = 127;
            String integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                try {
                    int i = parseInt(integerCacheHighPropValue);
                    i = Math.max(i, 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;
			// Created a cached array with a length of 256
            cache = new Integer[(high - low) + 1];
            int j = low;
            // 256 cycles
            for(int k = 0; k < cache.length; k++)
                // Create the Integer object corresponding to - 128 to 127 at one time and save it to the array
                cache[k] = new Integer(j++);

            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }

        private IntegerCache() {}
    }

Source code in valueOf(int)

    public static Integer valueOf(int i) {
        // If i is between - 128 and 127
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            // The Integer object created earlier is returned from the cached array
            return IntegerCache.cache[i + (-IntegerCache.low)];
        // Otherwise, create a new Integer object
        return new Integer(i);
    }

   reminder: the more seemingly simple interview questions, the more mysterious they are. The interviewer needs relatively deep skills.

8. Difference between & & and & &

&: bitwise AND

int a = 5;   //  101
int b = 3;   //  011
int c = a & b;// 001

   logic and: the result is true only if it is true. If it is false on the left, the expression on the right will still run

    & &: the result is true only when both short circuit and short circuit are true. If the left is false, the expression on the right will not run

    public static void main(String[] args) {
        int a = 5;   //  101
        int b = 3;   //  011
        int c = a & b;// 001
        System.out.println("c = " + c);
        // Logic and & if both sides are true, the result is true
        //  The left is false and the result is false, but the expression on the right will still operate
        if(a == 0 & a ++ > 0){
            System.out.println("------");
        }
        System.out.println("a = " + a);
        // &&If the short circuit and the left are false, the overall result is also false, and the expression on the right will not operate
        if(a == 0 && a ++ > 0){
            System.out.println("------");
        }
        System.out.println("a = " + a);
        String name = null;
        // Short circuit and are very useful in practical use
        if(name != null & !name.equals("")){

        }
    }
}

9. Data types that can be used by switch

Before JDK5: byte, short, int, char

After JDK5: enumeration types are introduced into Java, and enumeration types can also be used

After JDK7: String can be used, but long type is always not allowed

10. Use the most effective method to calculate 2 times 8?

   2 < < 3 (shift 3 bits left, equivalent to multiplying 2 to the power of 3)

11. Can the constructor be rewritten?

  constructors cannot be inherited and therefore cannot be overridden, but we can overload constructors

12. Can I inherit String class?

   String class is final type, so it cannot be inherited.

13. The difference between overloading and rewriting

   method overloading and rewriting are ways to realize polymorphism. The difference is that the former realizes compile time polymorphism, while the latter realizes run-time polymorphism.

   overloading: in the same class, methods with the same name are regarded as overloaded if they have different parameter lists (parameter type, number of parameters, order)

package com.bobo.interview0006;

public class Demo01 {
    public static void main(String[] args) {
        A a = new A();
        a.show1();
        a.show1(18);
        a.show1("a",18);
        a.show1(18,"aaa");
    }
}

class A{

    /**
     * Method overloading: the method name is the same and the parameter list is different in the same class
     */
    public void show1(){

    }

    public void show1(String name){

    }

    public void show1(int a){

    }
    public void show1(String name,int a){

    }

    public void show1(int a,String name){

    }
}

   override: occurs in a parent-child relationship class. The subclass overrides the method of the parent class and has the same return type or subclass

class B extends A{

    /**
     * Override, a subclass overrides a method in a parent class
     */
    @Override
    public void show1() {
        // super.show1();
        System.out.println("show1 --- B");
    }

    /**
     * The overridden return type must be the same or a subclass of the parent return type
     * @param n
     * @return
     */
    @Override
    public Integer fun1(Number n) {
        return 666;
    }
}

14. Differences between abstract classes and interfaces

  1. Neither interfaces nor abstract classes can be instantiated
  2. Compared with ordinary classes, the limitation of abstract classes is that abstract methods can be added
  3. Only constants and abstract methods can be declared in the interface, and the access modifiers must be public. After JDK8, default methods and static methods can be defined
package com.bobo.interview0007;

public class Demo01 {
    public static void main(String[] args) {

    }
}

/**
 * abstract class
 *   Cannot be instantiated
 *   You can declare common properties and methods
 *   You can also define abstract methods
 */
abstract class A{

    private int a;
    public int b;


    public void fun1(){

    }
    public abstract  void fun2();

}

/**
 * Interface
 *   Cannot be instantiated
 *   Property can only be a constant
 *   Methods can only be abstract methods
 *      JDK1.8 Then you can have default and static methods
 */
interface B{
     public final  int a = 9;
     // The default type of public abstract method may not be added
     public abstract void show1();

    /**
     * default method
     */
    public default void fun1(){

     }

    /**
     * Static method
     */
    public static void fun2(){

     }
}

15. Difference between static internal class and internal class

   static inner class is an inner class declared as static. It can be instantiated without relying on the instance of the outer class. Generally, our inner class can be instantiated only through the instance of the outer class.

public class OutterClass {

    /**
     * General internal class
     */
    class InnerClass{
        public void show(){
            System.out.println("InnerClass ...");
        }
    }

    /**
     * Static inner class
     */
    static class StaticInnerClass{
        public void show(){
            System.out.println("StaticInnerClass ...");
        }
    }
}

Test code

    public static void main(String[] args) {
        // Get ordinary inner class object
        OutterClass.InnerClass innerClass = new OutterClass().new InnerClass();
        innerClass.show();
        // Get static inner class object
        OutterClass.StaticInnerClass staticInnerClass = new OutterClass.StaticInnerClass();
        staticInnerClass.show();
    }

16. Can abstract methods be both static local methods and synchronized?

  the class of the abstract method must be an abstract class,

  1. It cannot be modified by static, because static cannot be overridden, and abstract methods must be overridden by subclasses, so it is contradictory.

  2. It cannot be modified by native. Local methods are implemented by C code, while abstract methods are not implemented, which is also contradictory

  3. It cannot be modified by synchronized. Synchronization is related to the details of method implementation, while abstract methods have no specific implementation, which is also contradictory

17. Differences between static variables and instance variables

Static variable: it is a variable modified by static, also known as class variable. It is an attribute class object and does not belong to any object of the class. Static variables are shared between objects

Instance variable: for an object with specific data, you must first create an object, and then access the instance variable through the object,

18. Can ordinary methods be accessed in static methods

   certainly not. Static methods are created in the class loading stage, while ordinary methods are attribute objects. There is no object in the class loading stage, so it is contradictory. Static methods can only access static members. Ordinary methods must first create objects and then call ordinary methods through objects.

public class Person {

    static void show(){
        // Ordinary methods cannot be called in static methods
       //  speak();
    }

    void speak(){
        // Normal methods can call static methods
        show();
    }
}

19. How to achieve cloning

Prototype modeexplain
Shallow cloningJust copy the object, and the array and reference object inside the object will not be copied, or point to the internal element address of the native object
Deep cloningDeep copy copies all the objects referenced by the object to be copied
package com.dpb.prototype;

import java.io.Serializable;
import java.util.Date;

/**
 * Prototype class: cloned type
 * @author dengp
 *
 */
public class User implements Cloneable,Serializable{
	
	private String name;
	
	private Date birth;
	
	private int age;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Date getBirth() {
		return birth;
	}

	public void setBirth(Date birth) {
		this.birth = birth;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
	
	/**
	 * Method for realizing cloning
	 */
	public Object clone() throws CloneNotSupportedException{
		return super.clone();
	}
}

Deep cloning

package com.dpb.prototype;

import java.io.Serializable;
import java.util.Date;

/**
 * Prototype class: cloned type
 * Deep cloning test
 * @author dengp
 *
 */
public class User2 implements Cloneable,Serializable{
	
	private String name;
	
	private Date birth;
	
	private int age;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Date getBirth() {
		return birth;
	}

	public void setBirth(Date birth) {
		this.birth = birth;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
	
	/**
	 * Method for realizing cloning
	 * Deep clone
	 */
	public Object clone() throws CloneNotSupportedException{
		Object object = super.clone();
		// Implement deep clone
		User2 user = (User2)object;
		user.birth = (Date) this.birth.clone();
		return object;
	}
}

serialization and deserialization

public static void main(String[] args) throws CloneNotSupportedException, Exception {
	Date date =  new Date(1231231231231l);
	User user = new User();
	user.setName("Bobo roast duck");
	user.setAge(18);
	user.setBirth(date);
	System.out.println("-----Properties of prototype object------");
	System.out.println(user);
	System.out.println(user.getName());
	System.out.println(user.getBirth());
	
	//Deep replication using serialization and deserialization
	ByteArrayOutputStream bos = new ByteArrayOutputStream();
	ObjectOutputStream    oos = new ObjectOutputStream(bos);
	oos.writeObject(user);
	byte[] bytes = bos.toByteArray();
	
	ByteArrayInputStream  bis = new ByteArrayInputStream(bytes);
	ObjectInputStream	  ois = new ObjectInputStream(bis);
	
	//Cloned object!
	User user1 = (User) ois.readObject();   
	
	// Modify the value of the prototype object
	date.setTime(221321321321321l);
	System.out.println(user.getBirth());
	
	System.out.println("------Properties of cloned objects-------");
	System.out.println(user1);
	System.out.println(user1.getName());
	System.out.println(user1.getBirth());
}

20. Introduce the final keyword

final modificationdescribe
classThis class cannot be inherited
methodThis method cannot be overridden
Member variableVariable is a constant and cannot be modified

21. Program running problem

The output of the following program is:

public class Hello {

    /**
     * Class object
     * Object Common object
     * Java The class loading mechanism should be clear
     * @param args
     */
    public static void main(String[] args) {
        A ab = new B(); // Normal objects are created based on Class objects 1a2b
        ab = new B(); // Because the class object of B has been loaded, the static variable initialization will not be executed 2b
        // 1a2b2b
    }
}
class A {
    static {
        System.out.print("1");
    }
    public A() {
        System.out.print("2");
    }
}

class B extends A{
    static {
        System.out.print("a");
    }
    public B() {
        super();
        System.out.print("b");
    }
}

The output result is:

1a2b2b

Sequence of program execution:

When the object is created, the calling sequence of the constructor is to initialize the static member first, then call the parent class constructor, then initialize the non static member, and finally call the self constructor.

22. Conversion between data types

  • String – basic data type
  • Basic data type – string
    public static void main(String[] args) {
        String s1 = "99";
        // Convert to int type
        // 1. Pass the parseXXX(String) method provided in the wrapper class Integer corresponding to int
        int i = Integer.parseInt(s1);
        // 2. Use the wrapper corresponding to int to the valueOf(String) method in Integer
        Integer i2 = Integer.valueOf(s1);

        // Convert a basic data type to String type
        int age = 18;
        String s2 = age + "";
        String s3 = String.valueOf(age);
    }

23. The execution order of return and finally

Analyze the following code program, give the output results and give the reasons

public class Demo02 {
    public static void main(String[] args) {
        Demo02 demo02 = new Demo02();
        System.out.println(demo02.getName("bobo"));
    }

    public String getName(String name){
        String res = "";
        try {
            res = name;
            return  res;
        }finally {
            res = "Bobo roast duck";
        }
    }
}

The output is bobo

Reason: through instruction analysis, we can find that when the return code is executed, the local variable will be saved at the top of the stack frame, and then the local variable of the original stack frame position will be modified in finally. The final returned information is still the variable at the top of the stack frame. Therefore, the finally code block will be executed after the return keyword, but the information at the top of the stack frame will not be changed.

There is another situation to note. What happens if there is a return keyword in both finally and try blocks?

public class Demo02 {
    public static void main(String[] args) {
        Demo02 demo02 = new Demo02();
        System.out.println(demo02.getName("bobo"));
    }

    public String getName(String name){
        String res = "";
        try {
            res = name;
            return  res;
        }finally {
            res = "Bobo roast duck";
            return res; // The data returned in the instruction is not the data at the top of the stack frame, but the stack frame position corresponding to res
        }
    }
}

   through the instruction, we can see that the instruction of the return keyword in finally returns the information of the local variables in finally. It can be understood that the return in finally will overwrite the return logic in the try block.

Keywords: Java Interview OOP set

Added by duclet on Mon, 07 Mar 2022 15:15:44 +0200