[JAVA] [] [Interview] Basics - the basics

Basics


Basic training

  • What is object-oriented

    Real-world tasks existing things can be called an object, object-oriented is a way of modeling the real world, to an abstract idea to a specific example, content features contained in the object are its properties, objects Some operating behavior is its methods. For example resume is an object, the contents of which are its properties, see, take, to put this method can be called an object.

  • Object-oriented features

    Package : a description of the object's attributes and behavior encapsulated into a class, the service specific logic function implemented as a method of encapsulation, encapsulation significance is followed by effective protection attribute property modifier privatization (member variables) by accessing, privatization method.

    Inheritance : implementation code reuse, all subclasses common extraction behavior and properties of a parent class, subclass inherits all the attributes and behavior of the parent class may be provided, having a succession of transfer and unity.

    Polymorphism : referenced in the definition of the specific type and specific method call type variable points can not be determined at compile phase, but in order to determine the specific reference type variable to point to the statement in which the object is invoked at runtime which class of method.

    Polymorphic forms are cast, up like shape, polymorphic polymorphic behavior can be divided into objects and polymorphism.

    • Polymorphic behavior: when there is different implementation methods, different object calls the same run () {}, when the cat call is run, when the fish swim call, when to call the birds are flying.

    • Object polymorphism: the same object, the shape may be a different type, such as the same person object that can be shaped to son, father, and other employees.

  • Seven of object-oriented design principles

    1. The opening and closing principle (the Open-Closed Principle, the OCP) :

    Software entity shall open for extension, but closed for modification. Without modifying existing code base up expansion of new features.

    2. Single Responsibility Principle (Single Responsibility Principle) :

    Define a class, you should have only one duty. If a class has more than one role, coupled with a plurality of functions, it will lead to design limitations and reusability of code.

    3. Richter substitution principle (Liskov. Substitution Principle) :

    Subtype must be able to replace their parent type. Subclass can extend the functionality of the parent class, but can not change the parent class of the original function. When the method of the parent class subclass overloaded, the pre-conditions of the process (i.e., process parameter) input parameters than the parent class method more relaxed. When subclass of the implementation of the abstract parent class, method postcondition (i.e., return value) is more stringent than the parent.

    4. Demeter (Law Of Demeter) :

    Demeter is also known as the least known principle that an object should be kept to a minimum understanding of other objects, only direct communication with friends. If the two classes do not have to communicate directly with each other, then the two classes can not be direct interaction. To minimize the coupling between a class and class. Software programming general principles: low coupling high cohesion. Demeter intention is to reduce the coupling between classes, each class is reduced due to the unnecessary reliance, therefore it does reduce coupling relationship.

    5. Dependency Inversion Principle (Dependence Inversion Principle)

    High-level modules should not depend on low-level modules, both of which should rely on its abstract; abstract should not rely on details; details should depend on the abstract. Dependency Inversion principle is to us oriented programming interface, understand programming to interfaces, also understand Dependency Inversion.

    6. Interface segregation principle (Interface Segregation Principle)

    The client should not rely on it does not interface; dependence on a class of a class should be based on the smallest interface.

    7. The synthetic / polymeric Principles (Composite / Aggregate Reuse Principle, CARP)

    Try to use synthetic / polymeric, try not to use inheritance. Principle: a class in another object.

  • High cohesive low coupling appreciated

内聚:每个模块尽可能独立完成自己功能,不依赖与模块外部的代码。

耦合:模块与模块之间接口的复杂程度,模块之间联系越复杂耦合度越高,牵一发而动全身。

低耦合是指减少对其他类的依赖,高内聚是指调用的方法尽量写在本类中,对一个项目来说,就是减少第三方依赖。
复制代码
  • The difference between final, finally, finalize the

    final: can be used to modify the class, method and variable (member variables or local variables)

    • Modified class: When the modified class, the surface of the class can not be inherited, note: final class method will implicitly define all the members of the final approach.
    • Modification method: the method to lock to prevent modification of their inheritance. final modified method can not be overridden. Note: If the parent class final method permissions for private, a subclass can not inherit, if the sub-class re-defined function the same name, which will be considered to be a new method in the subclass.
    • Modifying variables: final member variable represents a constant. It can only be assigned once, after the assignment and its value will not change. When a final modification of the basic data types, represents the value of the basic data types of changes can not occur once after initialization; if the final modification of a reference type, then it can not let its initialization after point to other objects, but the the reference in the object pointed to changes that may occur. final modification member variables must be initialized.

    the finally: the finally as part of the exception process can be used only in a try / catch statement, and is provided with a block of statements, the statements represented will be eventually executed.

    That several of the following situations will not be executed:

    • Call System.exit () method
    • JVM crashes (resulting in abnormal situations)

    the Finalize: the Finalize () is defined in java.lang.Object reason, that is, every object has such a method. This object when gc start, the object is recovered when they were called. In fact, most of the objects can be recycled gc (out of all new objects, gc can get), so generally do not need to finalize the realization.

  • The difference between int and Integer

    1. Is a wrapper class Integer int, int is a java basic data types.
    2. Integer variables must be instantiated before use, int variable is not required.
    3. Integer object is actually referenced, when a new Integer, is actually a pointer to the object; and int data value is stored directly.
    4. Integer default value is null, int default value is 0.
    public static void main(String[] args) {
        Integer i = 10;
        Integer j = 10;
        System.out.println(i == j);     //true
          
        Integer a = 128;
        Integer b = 128;
        System.out.println(a == b);     //false
         
        int k = 10;
        System.out.println(k == i);     //true
        int kk = 128;
        System.out.println(kk == a);    //true
          
        Integer m = new Integer(10);
        Integer n = new Integer(10);
        System.out.println(m == n);     //false
    }
    复制代码
  • Overloading and rewrite the difference

    Overload (Overloading): overload occurs in this class, the same method name, a list of different parameters, regardless of the return value, and only the method name, parameter list, the parameter of the relevant type.

    • Method name must be the same
    • Method's parameter list certainly is not the same
    • Access modifiers and return type may be the same or different

    Rewriting (Overriging): rewrite occurs between the parent and child classes, generally it indicates the relationship between parent and child classes.

    • Must be the same method name, return type must be the same
    • Parameter list must be the same
    • Access can not be lower than the parent class is rewritten access method. For example: a parent class declared as public, then the subclass can not be declared after rewriting protected.
  • The difference between abstract classes and interfaces

    Abstract class: abstract class modified with abstract, abstract class is used to capture the universal subclass, it can not be instantiated, used only as a superclass subclass abstract class is used to create a subclass inheritance hierarchy in stencil.

    Interface: Interface is a set of abstract methods, if a class implements an interface, then it inherited this abstract interface methods, like contract mode, if you implement this interface, so long it must ensure that the use of these methods, and implement these methods, the interface is a form of the interface itself can not do anything inside the interface methods are abstract of default.

    scenes to be used:

    • If you have some way and want some default concrete implementation of them, choose an abstract class.
    • If you want to implement multiple inheritance, then please use the interface, because the java does not support multiple inheritance, a subclass can not inherit multiple classes, but a class can implement multiple interfaces, so you can use the interface to solve.
    • If the basic functions are constantly changing, so long abstract class, if you use interface, each change requires a corresponding change to all classes that implement the interface.
    parameter Abstract class interface
    The default method implementation The default method can achieve Completely abstract, there is no way to achieve
    Method to realize Subclass use extends keyword to inherit the abstract class, subclass if not an abstract kind of thing,

    All the abstract methods in the parent class abstract class needs to implement it, the Central African abstract superclass method rewritable or not rewritable

    To achieve a subclass implements the interface, the interface need to implement all the methods
    Constructor An abstract class can have a constructor (not modified by the constructor abstract) Not have an interface constructor
    And the difference between normal Java class Normal Java class can be instantiated, abstract class that can not be instantiated Java classes and interfaces are normally different types
    Access modifier Abstract methods can be public, protected, default modifications Interface default is public, it can not be used to modify other modifiers
    main method An abstract class can have a main method, run Main method can interface
    Multiple Inheritance Abstract class inherit a class and implement multiple interfaces Interface can inherit one or more interfaces
  • Use talk and reflection achieved

    Reflection: Core reflected JVM is dynamically loaded or call methods / access properties at runtime, it requires no prior (to write code or compile) know who run the object yes. Note: Due to the reflective extra consume some system resources, so if you do not need to dynamically create an object, so long does not require reflection.

    Reflector frame functions provided:

    • Determining at runtime object belongs to any class;
    • At runtime class of an object in any configuration;
    • Analyzing any class has member variables and methods (or even by the reflection method can be called private) at runtime;
    • Call any of the object's method at run time

    Use reflection: reflection of the most important uses is to develop a variety of common framework.

    Basically reflected: get Class object to determine whether an instance of a class, create an instance, access methods, access to configuration information, access to member variables of the class, call the method, use reflection to create an array.

  • Talk about the scenes and custom annotation realization

    There are four java yuan notes:

    @Retention: definition of the annotation of the life cycle (when to use the comment)

    RetentionPolicy.RUNTIME: are never discarded runtime also reserve notes, so you can use reflection to read the annotation information. Custom, normally used when the note.

    @Inherited: definition of the relationship between the notes and subclass (subclass inherits whether to allow the notes), if used @Inherited a modified annotation type is used for a class, then this annotation will be used for the subclass of the class.

    @Documented: a simple Annotations mark notes, annotations indicating whether the information added to the java document (whether notes will be included in the JavaDoc)

    @Target: indicates that the notes used in any place (for notes where)

    ElementType.TYPE used to describe classes, interfaces (including type of annotation), or an enum declaration.

    
    @Retention(RetentionPolicy.RUNTIME)
    @Inherited
    @Documented
    @Target({ElementType.FIELD,ElementType.METHOD})
    @interface MyAnno{
        public String name() default "zhangsan";
        public String email() default "[email protected]";
    }
     
    //创建用户类
    class  User{
     
        @MyAnno(name = "zhang")
        private String name;
     
        @MyAnno(name = "[email protected]")
        private String email;
     
     
        @MyAnno(name = "sayHelloWorld")
        public String sayHello(){
            return "";
        }
    复制代码
  • The difference between GET and POST method of the HTTP request

    Get: generally used for acquiring, queries resource information

    POST: Generally used to update resource information

    Get request POST request
    Request parameters will be displayed in the address bar Request parameters are not displayed in the address bar
    Request body is empty Request is a request body parameters
    Request parameters are displayed in the first row request (GET / name = aaa) Request parameter is not displayed in the first row request (POST /)
    Request parameters are displayed in the address bar [unsafe] Address bar does not show the relative safety of a request parameter []
    Request parameter to put the first line, http request to the first line of the display 1kb Request parameter release request, somatic no size restriction request
    Request parameters can not request.setCharacterEncoding ( "gbk") to set the encoding request.setCharacterEncoding ( "gbk") is provided only code set request body
  • session and cookie difference

    1. session is stored on the server side, cookie stored on the client (browser).
    2. cookie is not very safe, people can analyze the local cookie store and cookie deception, taking into account the security should be used session.
    3. session will be saved on the server for a certain time. When accessing the increase would be more take up server performance, taking into account mitigating server performance, you should use the cookie.
    4. Single cookie saved data can not exceed 4k, many browsers are limited to a maximum of 20 sites saved cookie.
    5. May be considered to store login information and other important information for the session, additional information For reservations, you can put a cookie.
  • session Distributed Processing

    1. The client cookie encryption. (Generally used in enterprise network systems require the user cookie browser can not be disabled, disabled, the program will fail).
    2. Cluster, each application server provides session replication functionality, Tomcat and Jboss have achieved such a function. Specific: increase server performance with the sharp decline, likely to cause broadcast storms; session data needs to be serialized affect performance.
    3. session persistence, use the database to store the session. Even if the downtime did not matter, session database still exists. Features: Each session should request the database to read and write, will bring performance overhead. Use in-memory database will improve performance, but downtime can lose data (like Alipay downtime, disaster recovery have city, off-site disaster recovery).
    4. The use of shared storage to save the session. And similar databases, even if the downtime is also all right. In fact, specifically engaged in one server, all of the session floor. Specific: Frequent serialization and de-serialization can affect performance.
    5. Use memcached to save the session. Is essentially a memory database solutions. Features: Data stored in memcached need to be serialized, very low efficiency.
  • JDBC Process

    1. Registration driver: Class.forName ( "com.mysql.jdbc.Driver");
    2. Using the data to obtain management class drive connection object: conn = DriverManager.getConnection (...);
    3. Acquiring operation target database: Statement state = conn.createStatement ();
    4. SQl statement defines operations
    5. Performing state.executeQuery (sql);
    6. Result set: ResultSet, if the parameter value to the parameter value before the setXXX SQl ()
    7. Close object database resource recovery (result set is closed -> close the database operation target -> close the connection)
public class JDBCTest {
    /**
     * 使用JDBC连接并操作mysql数据库
     */
    public static void main(String[] args) {
        // 数据库驱动类名的字符串
        String driver = "com.mysql.jdbc.Driver";
        // 数据库连接串
        String url = "jdbc:mysql://127.0.0.1:3306/jdbctest";
        // 用户名
        String username = "root";
        // 密码
        String password = "1234";
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            // 1、加载数据库驱动( 成功加载后,会将Driver类的实例注册到DriverManager类中)
            Class.forName(driver);
            // 2、获取数据库连接
            conn = DriverManager.getConnection(url, username, password);
            // 3、获取数据库操作对象
            stmt = conn.createStatement();
            // 4、定义操作的SQL语句
            String sql = "select * from user where id = 100";
            // 5、执行数据库操作
            rs = stmt.executeQuery(sql);
            // 6、获取并操作结果集
            while (rs.next()) {
                System.out.println(rs.getInt("id"));
                System.out.println(rs.getString("name"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 7、关闭对象,回收数据库资源
            if (rs != null) { //关闭结果集对象
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (stmt != null) { // 关闭数据库操作对象
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) { // 关闭数据库连接对象
                try {
                    if (!conn.isClosed()) {
                        conn.close();
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
复制代码
  • MVC design ideas

MVC is the Model-View-Controller short, it is an architectural pattern, which separates the performance and interaction. The core is divided into three parts: model, view and controller.

Model(模型),是程序的主体部分,主要包含业务数据和业务逻辑。在模型层,还会涉及到用户发布的服务,在服务中会根据不同的业务需求,更新业务模型中的数据。

View(视图),是程序呈现给用户的部分,是用户和程序交互的接口,用户会根据具体的业务需求,在View视图层输入自己特定的业务数据,并通过界面的事件交互
将对应的输入参数提交给后台控制器进行处理。

Controller(控制器),Controller是用来处理用户输入数据,以及更新业务模型的部分。控制器中接收了用户与界面交互时传递过来的数据,并根据数据业务逻辑来
执行服务的调用和更新业务模型的数据和状态。

MVC架构的控制流程
1.所有的终端用户请求被发送到控制器。
2.控制器依赖请求去选择加载哪个模块,并把模型附加到对应的视图。
3.附加了模型数据的最终视图做为相应发送给终端用户。
复制代码
  • The difference equals and ==

    When compared to basic data types, but to use ==, the comparison value

    When comparing reference data types, == is a reference address comparison, and actually equals, equals method of Object defined, the default display is relatively address. We used a String type because rewrite the equals method that compares the contents inside.

Guess you like

Origin juejin.im/post/5d2d21bae51d4555fd20a3fb