Java object-oriented interview collection

Java object-oriented: here is the basic object-oriented knowledge to help you learn and understand. I hope it can help you. Here is the relevant knowledge sorted according to the company's interview data:

The difference between overload and override. Can the overloaded method change the type of the return value?

Overload means overloading, and override means overriding, that is, rewriting. Overloaded overload means that there can be multiple methods with the same name in the same class, but the parameter lists of these methods are different (that is, the number or type of parameters are different).

Overriding override means that the method in the subclass can have the same name and parameters as a method in the parent class. When calling this method through the instance object created by the subclass, the defined method in the subclass will be called, which is equivalent to overriding the exactly same method defined in the parent class. This is also a manifestation of polymorphism in object-oriented programming.

Override can be translated as override. Literally, it overrides a method and rewrites it to achieve different functions. For us, the most familiar coverage is the implementation of interface methods. Generally, only methods are declared in the interface, and we need to implement all the methods declared by the interface when we implement them. In addition to this typical usage, we may override the methods in the parent class in the subclass in inheritance. Pay attention to the following points in coverage:

1. The flag of the covered method must match the flag of the covered method to achieve the effect of coverage; 2. The return value of the overridden method must be consistent with that of the overridden method; 3. The exception thrown by the covered method must be consistent with the exception thrown by the covered method, or its subclass; 4. The overridden method cannot be private. Otherwise, only a new method is defined in its subclass and is not overridden.

Overload can be translated as overload, which means defining some methods with the same name, distinguishing these methods by defining different input parameters, and then when calling again, the VM will select the appropriate method to execute according to different parameter styles. The following points should be paid attention to when using overload:

1. When using overloading, you can only use different parameter styles. For example, different parameter types, different parameter numbers and different parameter orders (of course, several parameter types in the same method must be different, for example, can be fun (int, float), but can not be fun (int, int)); 2. It cannot be overloaded by access permission, return type and thrown exception; 3. The exception type and number of methods will not affect overloading; 4. For inheritance, if a method is priavte in the parent class, it cannot be overloaded in the child class. If it is defined, it only defines a new method, which will not achieve the effect of overloading.

If the parameter lists of several overloaded methods are different, their returner types can be different. If the parameter lists of the two methods are exactly the same, overload can not be realized by different return values. We can use the method of counter evidence to illustrate this problem. For example, we call map When using the remove (key) method, although the remove method has a return value, we usually do not define the variable that receives the return result. At this time, assuming that there are two methods with exactly the same name and parameter list in the class, Java can't determine which method the programmer wants to call, because it can't judge by the return result type.

Can the constructor be overridden?

Constructor cannot be inherited, so override cannot be overridden, but overload can be overridden.

Is the interface inheritable? Can abstract classes implement interfaces? Can abstract classes inherit concrete classes? Can there be static main methods in abstract classes?

Interfaces can inherit interfaces. Abstract classes can implement interfaces. Abstract classes can have static main methods.

The only difference between abstract classes and ordinary classes is that instance objects cannot be created and abstract methods are allowed.

When writing the clone () method, there is usually a line of code. What is it?

Clone () method is cloning, that is, copying objects; That is, there is already an object a, in which a contains some valid values, but you want to have an object B, and any change to B will not affect the value in a, but B is not a new object created by new.

Copy: ① a copy object returns a new object instead of a reference. ② The difference between the copied object and the object returned by the new operator is that the copied object already contains the information of the original object rather than the initial information of the object

Clone has a default behavior, super clone(); Because the members in the parent class should be copied in place first, and then their own members should be copied.

What are the characteristics of object-oriented

Object oriented programming language has four main characteristics: encapsulation, inheritance, abstraction and polymorphism.

1 package:

Encapsulation is the basis to ensure the excellent modularity of software components. The goal of encapsulation is to achieve "high cohesion and low coupling" of software components and prevent the change impact caused by program interdependence. In object-oriented programming language, object is the most basic unit of encapsulation. Object-oriented encapsulation is clearer and more powerful than traditional language encapsulation. Object oriented encapsulation is to encapsulate the code describing the attributes and behavior of an object in a "module", that is, a class. Attributes are defined by variables and behaviors are defined by methods. Methods can directly access the attributes in the same object. Generally, as long as you remember to put the variable and the method accessing the variable together, and define all the member variables in a class as private, only the class's own method can access these member variables, which basically realizes the encapsulation of objects. Grasp a principle: put the methods and related methods operating on the same thing in the same class, and put the method and the data it operates in the same class.

2. Abstraction:

Abstraction is to find out the similarities and commonalities of some things, and then classify these things into a class. This class only considers the similarities and commonalities of these things, ignores those aspects unrelated to the current theme and goal, and focuses on those aspects related to the current goal. For example, when you see an ant and an elephant, you can imagine that they have the same thing, that is, abstraction. Abstraction includes behavior abstraction and state abstraction. For example, define a person class as follows:

People are originally very complex things with many aspects, but because the current system only needs to understand people's name and age, the class defined above only contains the two attributes of name and age. This is a kind of abstraction. Using abstraction can avoid considering some details irrelevant to the goal.

3. Succession:

When defining and implementing a class, it can be based on an existing class, take the content defined by the existing class as its own content, add some new content, or modify the original method to make it more suitable for special needs, which is inheritance. Inheritance is a mechanism for subclasses to automatically share parent class data and methods. It is a relationship between classes, which improves the reusability and scalability of software.

4 polymorphism:

Polymorphism refers to the specific type pointed to by the reference variable defined in the program and the method call issued through the reference variable. It is not determined during programming, but only during the running of the program, that is, a reference variable will point to the instance object of which class, and the method call issued by the reference variable is the method implemented in which class, It can only be determined during the running of the program. Because the specific class is determined only when the program is running, the reference variable can be bound to various class implementations without modifying the source program code, resulting in the change of the specific method called by the reference, that is, the specific code bound when the program is running can be changed without modifying the program code, so that the program can select multiple running states, This is polymorphism. Polymorphism enhances the flexibility and scalability of software. For example, userdao in the following code is an interface that defines the instance object pointed to by the reference variable userdao, which is defined by daofactory GetDao () returns when executing. Sometimes it points to the implementation of userjdbcdao, and sometimes it points to the implementation of userhibernatedao. In this way, the specific class implementation pointed to by userdao can be changed without modifying the source code, resulting in userdao The specific code of the insertuser() method is also changed, that is, sometimes the insertuser method of userjdbcdao is called, and sometimes the insertuser method of userhibernatedao is called:

UserDao userDao = daofactory. getDao(); userDao. insertUser(user);

What is the mechanism of polymorphism in Java?

It depends on that the reference variable defined by the parent class or interface can point to the instance object of the subclass or specific implementation class, and the method called by the program is dynamically bound at runtime, that is, the method of the specific instance object pointed to by the reference variable, that is, the method of the object running in memory, rather than the method defined in the type of the reference variable.

What is the difference between abstract class and interface?

A class with an abstract modifier is an abstract class. An abstract class cannot create an instance object. A class containing an abstract method must be defined as an abstract class, and the methods in an abstract class need not be abstract. The abstract methods defined in the abstract class must be implemented in concrete subclasses. Therefore, there can be no abstract construction methods or abstract static methods. If the subclass does not implement all the abstract methods in the abstract parent class, the subclass must also be defined as abstract type. An interface can be described as a special case of an abstract class, and all methods in the interface must be abstract. The method definition in the interface is public abstract by default, and the member variable type in the interface is public static final by default.

Grammatical differences between the two:

1. Abstract classes can have constructors, but interfaces cannot have constructors. 2. There can be ordinary member variables in the abstract class, but there are no ordinary member variables in the interface. 3 Abstract classes can contain non Abstract ordinary methods. All methods in the interface must be abstract and cannot have non Abstract ordinary methods. 4. The access type of the abstract method in the abstract class can be public, Protected and (default type, although eclipse does not report errors, it should not), but the abstract methods in the interface can only be public type, and the default is public abstract type. 5. The abstract class can contain static methods, and the interface cannot contain static methods. 6. Both the abstract class and the interface can contain static member variables, and the access types of static member variables in the abstract class You can use any variable, but the variables defined in the interface can only be public static final, and the default is public static final. 7. A class can implement multiple interfaces, but can only inherit one abstract class.

Application differences between the two:

The interface plays a role in the system architecture design method, which is mainly used to define the communication contract between modules. Abstract classes play a role in code implementation and can realize code reuse. For example, template method design pattern is a typical application of abstract classes. Assuming that all servlet classes of a project need to judge permissions, record access logs and handle exceptions in the same way, an abstract base class can be defined, Let all servlets inherit this abstract base class. In the service method of the abstract base class, complete the code for permission judgment, recording access logs and handling exceptions. In each subclass, only complete their own business logic code. The pseudo code is as follows:

If a piece of code in the middle of the parent method is uncertain and left to the subclass, the template method is used to design the pattern.

Can the method of abstract be static, native and synchronized at the same time?

The abstract method cannot be static, because abstract methods are implemented by subclasses, and static has nothing to do with Subclasses!

Native method means that the method should be implemented in another platform dependent programming language, and there is no problem of being implemented by subclasses. Therefore, it can not be abstract or mixed with abstract. For example, the fileoutputstream class needs to deal with hardware. The underlying implementation uses the API implementation related to the operating system. For example, it is implemented in C language in windows. Therefore, looking at the source code of JDK, you can find that the open method of fileoutputstream is defined as follows: private native void open (string name) throws FileNotFoundException;

If we want to use java to call other people's C language functions, we can't call them directly. We need to write a C language function according to the requirements of Java, and our c language function calls other people's C language functions. Since our c language function is written according to the requirements of Java, our c language function can be connected with Java. The connection method of Java is to define the method corresponding to our c function. The corresponding method in Java does not need to write specific code, but it needs to declare native in the front.

For synchronized, the synchronization lock object used for synchronized synchronization on the method is this, but the abstract method cannot determine what this is.

What is an inner class? The difference between static nested class and inner class.

An internal class is a class defined inside a class. Static members cannot be defined in an internal class. Static members are not the characteristics of an object. They need to be placed in a class just to find a place to live. The internal class can directly access the member variables in the external class, and the internal class can be defined outside the methods of the external class, It can also be defined in the method body of an external class, as shown below:

The access types of the internal class defined outside the method body can be public, protect, and default private, just as the member variables defined in the class have four access types, which determine whether the definition of the internal class is visible to other classes; In this case, we can also create the instance object of the internal class outside. When creating the instance object of the internal class, we must first create the instance object of the external class, and then use the instance object of the external class to create the instance object of the internal class. The code is as follows:

Outer outer = new Outer(); Outer. Inner1 inner1 = outer. new Innner1();

The internal class defined inside the method cannot be preceded by an access type modifier, just like the local variable defined in the method, but the final or abstract modifier can be used in front of this internal class. This internal class is invisible to other classes. Other classes cannot reference this internal class, but the instance object created by this internal class can be passed to other classes for access. This internal class must be defined first and then used, that is, the definition code of the internal class must appear before using the class, which is the same as the principle that the local variables in the method must be defined first and then used. This internal class can access a local variable in the method body, but the local variable must be preceded by the final modifier.

In the method body, you can also use the following syntax to create an anonymous internal class, that is, while defining a subclass of an interface or class, you can also create an instance object of the subclass without defining a name for the subclass:

Finally, the static keyword can be added in front of the internal class defined outside the method to become the static nested class. It no longer has the characteristics of the internal class. In a narrow sense, it is not an internal class. There is no difference between static nested class and ordinary class in runtime behavior and function, but there are some differences in syntax when programming reference. It can be defined as public, protected, default, private and other types, while ordinary classes can only be defined as public and default types. The name of static nested class referenced outside is "external class name. Internal class name". You can directly create a static nested class without creating an instance object of an external class. For example, assuming that inner is a static nested class defined in outer class, you can use the following statement to create inner class:

Outer. Inner inner = new Outer. Inner();

Since static nested class does not depend on the instance object of the external class, static nested class can access non static member variables of the external class. When accessing static nested class in an external class, you can directly use the name of static nested class without adding the name of the external class. In static nested class, you can also directly reference the static member variable of the external class without adding the name of the external class. The internal class defined in the static method is also static nested class. At this time, the static keyword cannot be added in front of the class. The application method of static nested class in the static method is very similar to that of the internal class in the ordinary method. It can access not only the static member variables in the external class, but also the local variables in the static method, The local variable must be preceded by the final modifier.

Can an inner class reference the members of its containing class? Are there any restrictions?

Absolutely. If it is not a static inner class, there are no restrictions!

If you regard the static nested class as a special case of the inner class, in this case, you can not access the ordinary member variables of the outer class, but only the static members in the outer class. For example, the following code:

Can anonymous inner class extend other classes and implement interface?

You can inherit other classes or implement other interfaces. Not only can, but must!

For example:

The result is test

In the test method, call getClass () directly The getName () method returns the Test class name. Because getClass () is defined as final in the Object class, the subclass can not override the method, so getClass () is called in the test method. The getname () method is actually calling the getClass () method inherited from the parent class, which is equivalent to calling super getClass(). Getname () method, so super getClass(). The getname () method should also return test. If you want to get the name of the parent class, you should use the following code:

getClass(). getSuperClass(). getName();

What is the difference between object oriented and process oriented

1. Different starting points. Object oriented method is to deal with the problems of the objective world in a way consistent with conventional thinking. It emphasizes that the essentials of the problem domain are directly mapped to the interface between objects. The process oriented method emphasizes the abstraction and modularization of the process. It takes the process as the center to construct or deal with the objective world problems.

2. The hierarchical logic is different. The object-oriented method uses computer logic to simulate the physical existence in the objective world, takes the set class of objects as the basic unit to deal with problems, and makes the computer world close to the objective world as much as possible, so as to make the problem processing more direct, clear and direct. The object-oriented method uses the hierarchical structure of classes to reflect the inheritance and development between classes, The basic unit of object-oriented process method is to express the process module clearly and accurately, summarize the relationship and function between modules or modules with the hierarchical structure of modules, and abstract the problems in the objective world into a process that can be processed by computers

3. The data processing mode is different from the control program mode. The object-oriented method encapsulates the data and the corresponding code into a whole. In principle, other objects cannot directly modify their data, that is, the modification of objects can only be completed by their own member functions. The control program is activated and run through "event driven". The object-oriented process processes the data directly through the program, and displays the processing results after processing. In the control program mode, it calls or returns the program according to the design, which can not be navigated. There is a relationship between control and controlled, call and called between each module.

4. The analysis design is different from the coding conversion mode. Object oriented method runs through the analysis of software life cycle. Design and coding is a smooth process. Consistent model display is adopted from analysis to design and then to coding, that is, a seamless connection is realized. The object-oriented process method emphasizes the transformation between analysis, design and coding according to rules. It realizes a kind of seamless connection through the analysis, design and coding of software life cycle.

What are the advantages of object-oriented development

1. High development efficiency. Using object-oriented development, we can abstract the real things and directly map the real practice to the developed objects.

2 to ensure the robustness of software, it is precisely because the object-oriented development method has high reusability, and the existing code that has been tested in related fields can be reused in the development process. Therefore, it naturally plays a good role in promoting the robustness of software.

3. Ensure the high maintainability of the software. Due to the object-oriented development mode, the readability of the code is very good. At the same time, the object-oriented design mode makes the code structure more clear. At the same time, there are many very mature design modes for the object-oriented development mode. These design modes can make the program only need to modify some modules to meet the requirements in the face of changes in requirements, Because it is more convenient to maintain.

What is the difference between this and super

In Java language, this refers to the current instance object, One of its very important functions is to distinguish the member variables of an object from the formal parameters of a method (when the name of a method's shape participating member variable is the same, it will overwrite the member variable). Super can be used to access the method or member variable of the parent class. When the method or member variable of the child class has the same name as the parent class, it will also overwrite the method or member variable of the parent class. To access the method or member variable of the parent class, you can only access it through the super keyword

How to get the class name of the parent class

The Java language provides a method to get the class name: getclass() Getname(), the developer can call this method to get the class name. But for inheritance, you can't call getClass () of the parent class Getname() method to get the class name of the parent class, for example:

The running result of the program is test. The reason is that any class in the Java language inherits from the object class. The getClass method is defined as final and native in the object class. Subclasses cannot override this method. So this GetClass () and super GetClass () eventually calls the getClass () method in the object class of the The definition of getClass () method in object class is to return the runtime class of this object. The name code of the parent class can be obtained in the subclass through the reflection mechanism of Java, as follows:

What is the difference between composition and inheritance

Composition and inheritance are two ways of code reuse in object-oriented. Composition refers to creating objects of the original class in a new class and reusing the functions of the existing class. Inheritance is one of the main features of object-oriented, which allows designers to define the implementation of a class according to the implementation of other classes. Both composition and inheritance allow setting child objects in new classes, but composition is displayed and inheritance is implicit. There is a corresponding relationship between composition and inheritance: the overall class in composition corresponds to the subclass in inheritance, and the local class in composition corresponds to the parent class in inheritance. The following two principles shall be followed when using:

Unless there is an "is-a" relationship between two classes, do not use inheritance easily, because excessive use of inheritance will destroy the maintainability of code. When the parent class is modified, it will affect all subclasses inherited from it.

2. Don't use inheritance just to achieve polymorphism. If the relationship between classes is not "is-a", you can achieve the same purpose by implementing interface and composition. Because the Java language only supports single inheritance, if you want to inherit two or more classes at the same time, it cannot be directly implemented in Java. At the same time, in the Java language, if you inherit too much, the content in a class will become bloated. Therefore, in the Java language, if you can use combination, you should try not to use inheritance.

Thank you for reading, hope to help you, thank you for your support to this site!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>