java object-oriented: Here we organize the basic knowledge of object-oriented to help everyone learn and understand. I hope it can help everyone. Here are the relevant knowledge compiled based on company interview information:
The difference between Overload and Override. Can the Overloaded method change the type of the return value?
Overload means overload, and Override means overwrite, that is, rewrite. Overloading 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 (i.e., the number or type of parameters are different).
Rewriting Override means that the method in the subclass can be exactly the same as the name and parameters of a method in the parent class. When this method is called through the instance object created by the subclass, the definition method in the subclass will be called, which is equivalent to overwriting the exactly the same method defined in the parent class. This is also a manifestation of the polymorphism of object-oriented programming.
override can be translated as override. As you can literally know, it is overriding a method and rewriting it in order to achieve different functions. The most familiar override for us is the implementation of interface methods. In an interface, the method is generally declared, and when we implement it, we need to implement all methods of interface declaration. In addition to this typical usage, we may also override methods in the parent class in inheritance. The following points should be paid attention to during coverage:
1. The logo of the overlay method must be exactly matched with the logo of the overlay method in order to achieve the effect of overlay;
2. The return value of the overwritten method must be consistent with the return of the overwritten method;
3. The exception thrown by the overwritten method must be consistent with the exception thrown by the overwritten method, or it is a subclass;
4. The overwritten method cannot be private, otherwise only a new method is defined in its subclass and it is not overwritten.
Overload can be translated as overloading, which means defining some methods with the same name, distinguishing these methods by defining different input parameters, and then when called, the VM will select the appropriate method to execute according to different parameter styles. When using overloading, please pay attention to the following points:
1. When using overloading, you can only pass different parameter styles. For example, different parameter types, different number of parameters, and different parameter orders (of course, several parameter types in the same method must be different, for example, it can be fun(int,float), but it cannot be fun(int,int));
2. Cannot be overloaded through access permissions, return types, and thrown exceptions;
3. The exception type and number of methods will not affect overloading;
4. For inheritance, if a method has access rights in the parent class and is priavte, then it cannot be overloaded in the subclass. If defined, it only defines a new method and will not achieve the effect of overloading.
If the parameter list of several Overloaded methods is different, their returner types may be different. If the parameter list of the two methods is exactly the same, overloading overload cannot be achieved by different return values. We can use the reverse proof method to illustrate this problem. For example, when we call the map.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 in this class with exactly the same name and parameter list, just because the return type is different, Java cannot determine which method the programmer wants to call, because it cannot be judged by returning the result type.
Can the constructor be override?
The constructor constructor cannot be inherited, so Override cannot be overridden, but Overload can be overloaded.
Can an interface be inherited? Can an abstract class implements an interface? Can an abstract class inherit concrete class? Can an abstract class exist? Can an abstract class have a static main method in an abstract class?
Interfaces can inherit interfaces. Abstract classes can implement (implements) interfaces. There can be static main methods in abstract classes.
The only difference between abstract classes and ordinary classes is that they cannot create instance objects and allow abstract methods.
When writing the clone() method, there is usually a line of code. What is it?
The Clone() method is to clone, which means copying the object; that is, there is already object A, where A contains some valid values, but if you want to have an object B, and any changes to B will not affect the value in A, but B is not a new object that is new.
Copy: ① The copy object returns a new object, not a reference. ②The difference between copying an object and the object returned with the new operator is that the copy already contains the original object's information, rather than the initial information of the object.
clone has a default behavior, super.clone(); because first, the members in the parent class must be copied into place, and then the members of it are copied.
What are the aspects of object-oriented features
Object-oriented programming languages include four main features: encapsulation, inheritance, abstraction, and polymorphism.
1 Package:
Packaging is the basis for ensuring that software components have excellent modularity. The goal of packaging is to achieve "high cohesion and low coupling" of software components to prevent the changes caused by program interdependence. In object-oriented programming languages, objects are the most basic unit of encapsulation, and object-oriented encapsulation is clearer and more powerful than traditional language encapsulation. Object-oriented encapsulation is to encapsulate the code that describes the properties and behavior of an object in a "module", that is, in a class. The properties are defined by variables and the behavior is defined by methods. The method can directly access the properties in the same object. Generally speaking, just remember to put the variable and the method of accessing this variable together, define all member variables in a class as private, and only the class's own methods can access these member variables, which basically implements the encapsulation of the object. Grasp a principle: put the methods and related methods that operate on the same thing in the same class, and put the methods and the data that operate on the same class.
2. Abstract:
Abstraction is to find out the similarities and commonalities of some things, and then classify them into a class that only considers the similarities and commonalities of these things, and ignores aspects that are not related to the current topic and goal, and focus on aspects that are related to the current goal. For example, seeing an ant and an elephant and you can imagine what they are like, that is abstraction. Abstraction includes two aspects: behavioral abstraction and state abstraction. For example, define a Person class as follows:
class Person{ String name; int age; } Humans are originally very complex things and have many aspects, but because the current system only needs to understand the name and age of a person, the class defined above only contains the attributes of name and age. This is an abstraction. Using abstraction can avoid considering some details that are not related to the goal.
3. Inheritance:
When defining and implementing a class, it can be done based on an existing class, and the content defined by the existing class is taken as its own content, and several new content can be added, or the original method can be modified to make it more suitable for special needs. This is inheritance. Inheritance is a mechanism by which subclasses automatically share parent class data and methods. This is a relationship between classes, which improves the reusability and scalability of software.
4 polymorphisms:
Polymorphism refers to the specific type pointed to by the reference variable defined in the program and the method calls issued through the reference variable are not determined during programming, but are determined during the program's run, that is, which class instance object a reference variable will point to, and which class method calls issued by the reference variable are implemented in which method can only be determined during the program's run. Because the specific class is determined only when the program is running, the reference variables can be bound to various different class implementations without modifying the source program code, which leads to the specific method of the reference call changing accordingly. That is, the specific code bound to the program run without modifying the program code, so that the program can select multiple running states, which is polymorphism. Polymorphism enhances the flexibility and scalability of the software. For example, the UserDao in the following code is an interface that defines the instance object pointed to by the reference variable userDao and is returned by daofactory.getDao() when executed. Sometimes it points to the implementation of UserJdbcDao, and sometimes it points to the implementation of UserHibernateDao. In this way, you can change the specific class implementation pointed to by userDao without modifying the source code, resulting in the specific code of the userDao.insertUser() method also changes accordingly. That is, sometimes it is called the insertUser method of UserJdbcDao, and sometimes it is called the insertUser method of UserHibernateDao:
UserDao userDao = daofactory.getDao(); userDao.insertUser(user);
What is the mechanism for implementing polymorphism in Java?
The reference variable defined by the parent class or interface can point to the instance object of the subclass or concrete implementation class, and the method called by the program is dynamically bound during the runtime. It is the method that refers to the specific instance object pointed to by the variable, that is, the method of the object that is 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 containing abstract modifier is an abstract class, an instance object that cannot be created by abstract class. Classes containing abstract methods must be defined as abstract class, and methods in abstract class classes do not have to be abstract. The definition of abstract methods in the abstract class class must be implemented in the Concrete subclass, so there cannot be abstract constructors or abstract static methods. If the subclass does not implement all abstract methods in the abstract parent class, the subclass must also be defined as the abstract type.
An interface can be said to be a special case of an abstract class, and all methods in an interface must be abstract. The method definition in the interface defaults to the public abstract type, and the member variable type in the interface defaults to the public static final.
The grammatical difference between the two:
1. Abstract classes can have construction methods, but not in interfaces.
2. There can be ordinary member variables in abstract classes, 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 there cannot be non-abstract ordinary methods.
4. The access types of abstract methods in abstract classes can be public, protected and (the default type, although there is no error in eclipse, it should not work), but the abstract methods in the interface can only be of public type, and the default is the public abstract type.
5. Abstract classes can contain static methods, but interfaces cannot contain static methods.
6. Both abstract classes and interfaces can contain static member variables. The access type of static member variables in abstract classes can be arbitrary, but the variables defined in the interface can only be public static final type, and the default is the public static final type.
7. A class can implement multiple interfaces, but can only inherit one abstract class.
The difference between the two in application:
Interfaces play a role in system architecture design methods, mainly used to define communication contracts between modules. Abstract classes play a role in code implementation and can realize the reuse of code. For example, the template method design pattern is a typical application of abstract classes. Assuming that all Servlet classes in a certain project must use the same method to make permission judgments, record access logs and handle exceptions, then you can define an abstract base class, so that all Servlets can inherit this abstract base class, complete permission judgments, record access logs and handle exceptions in the service method of the abstract base class, and only complete their respective business logic codes in each subclass. The pseudo-code is as follows:
public abstract class BaseServlet extends HttpServlet{ public final void service(HttpServletRequest request, HttpServletResponse response) throws IOExcetion,ServletException { Record access log for permission judgment if (with permission){ try{ doService(request,response);} catch(Excetpion e) { Record exception information}} } protected abstract void doService(HttpServletRequest request, HttpServletResponse response) throws IOExcetion,ServletException; //Note that access permission is defined as protected, which seems both professional and rigorous, because it is } public class MyServlet1 extends BaseServlet{protected void doService(HttpServletRequest request, HttpServletResponse response) throws IOExcetion,ServletException { specific business logic codes that this Servlet only processes} }A certain piece of code in the middle of the parent class method is uncertain, so I leave it to the subclass, so I use the template method to design the pattern.
Can abstract method be static at the same time, can it be native at the same time, and can it be synchronized at the same time?
The method of abstract cannot be static, because abstract methods must be implemented by subclasses, and static has nothing to do with subclasses!
The native method means that the method needs to be implemented in another platform-dependent programming language, and there is no problem of subclass implementation, so it cannot be abstract and cannot be mixed with abstract. For example, the FileOutputSteam class needs to be dealt with hardware, and the underlying implementation uses operating system-related API implementations. For example, it is implemented in C language in Windows. Therefore, looking at the source code of jdk, you can find that the definition of the open method of FileOutputStream is as follows: private native void open(String name) throws FileNotFoundException;
If we want to use java to call the C language function written by others, we cannot call it directly. We need to write a C language function according to the requirements of java, and our C language function will call 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 to Java. The docking method on Java is to define the method corresponding to our C function. The corresponding methods in Java do not need to write specific code, but native needs to be declared earlier.
For synchronized, the synchronization lock object used by synchronized synchronization on the method is this, and the abstract method cannot determine what this is.
What is an internal class? Static Nested Class is different from 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 just need to find a place to live, so they need to be placed in a class. The internal class can directly access member variables in the external class. The internal class can be defined outside the methods of the external class or in the method body of the external class, as shown below:
public class Outer{ int out_x = 0; public void method() { Inner1 inner1 = new Inner1(); public class Inner2 //Inner class defined inside the method body { public method() { out_x = 3; } } Inner2 inner2 = new Inner2(); } public class Inner1 //Inner class defined outside the method body { }} The access types of the inner class defined outside the method body can be public, protected, and default private. This is like the member variables defined in the class have 4 access types, which determine whether the definition of the inner class is visible to other classes. In this case, we can also create an instance object of the inner class outside. When creating an instance object of the inner class, we must first create an instance object of the outer class, and then use the instance object of the outer class to create an instance object of the inner class. The code is as follows:
Outer outer = new Outer();
Outer.Inner1 inner1 = outer.new Innner1();
There cannot be access type modifiers before the inner class defined inside the method, just like local variables defined in the method, but the final or abstract modifiers can be used before the inner class. This inner class is not visible to other classes and cannot refer to this inner class, but the instance objects created by this inner class can be passed to other classes to access. This kind of 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 local variables in the method must be defined first and then used. This inner class can access local variables in the method body, but the final modifier must be added before the local variable.
In the method body, the following syntax can be used to create an anonymous inner class, that is, while defining a certain interface or subclass of a class, an instance object of the subclass is also created without defining a name for the subclass:
public class Outer{ public void start() { new Thread( new Runable(){ public void run(){}; }).start(); }} Finally, you can prefix the inner class defined outside the method to add the static keyword to the Static Nested Class. It no longer has the characteristics of the inner class. All, in a narrow sense, is not an inner class. Static Nested Class is no different in the behavior and function of ordinary classes at runtime, but there are some differences in syntax when programming references. 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 the Static Nested Class class outside is "External Class Name.Inner Class Name". You can create a Static Nested Class directly without creating an instance object of an external class outside. For example, if Inner is a Static Nested Class defined in the Outer class, you can use the following statement to create the Inner class:
Outer.Inner inner = new Outer.Inner();
Since static Nested Class does not rely on instance objects of external classes, static Nested Class can access non-static member variables of external classes. When accessing Static Nested Class in an external class, you can directly use the name of the Static Nested Class without adding the name of the external class. In Static Nested Class, you can also directly refer to the static member variables of the external class without adding the name of the external class.
The inner class defined in a static method is also a Static Nested Class. At this time, you cannot add the static keyword before the class. The Static Nested Class in a static method is very similar to the application method of the inner class in ordinary methods. In addition to directly accessing the static member variables in the external class, it can also access local variables in the static method. However, the final modifier must be added before the local variable.
Can an inner class reference its members of the containing class? Are there any restrictions?
It's totally OK. If it is not a static inner class, there is no limit!
If you treat static nested classes as a special case of inner classes, in this case, you cannot access ordinary member variables of the outer class, but only static members in the outer class. For example, the following code:
class Outer{ static int x; static class Inner { void test() { syso(x); } }}}Anonymous Inner Class (anonymous internal class) Can extends (inherit) other classes, and can implements (implement) interface (interface)?
You can inherit other classes or implement other interfaces. Not only can, but must!
For example:
import java.util.Date;public class Test extends Date{ public static void main(String[] args) { new Test().test(); } public void test(){ System.out.println(super.getClass().getName()); }} The result is Test
In the test method, the getClass().getName() method is called directly, and the test class name is returned. Since getClass() is defined as final in the Object class, the subclass cannot overwrite the method. Therefore, calling getClass().getName() method in the test method is actually calling the getClass() method inherited from the parent class, which is equivalent to calling the super.getClass().getName() method. Therefore, the super.getClass().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
1The starting point is different. The object-oriented approach is to deal with the issue of the objective world in a way that conforms to conventional thinking. It emphasizes that the key points of the problem domain are directly alluded to the interface between objects. The process-oriented approach emphasizes the abstraction and modularity of the process, which is a process-centered construction or dealing with objective world problems.
2. The object-oriented method uses computer logic to simulate the physical existence in the objective world, and uses the object collection class as the basic unit for handling problems, so as to make the computer world closer to the objective world as much as possible, so as to make the problem handling more direct and clear. The object-oriented method uses the class hierarchy to reflect the inheritance and development between classes, while the object-oriented process method handles problems with the basic unit that enables the module that clearly and accurately expresses the process, uses the module hierarchy to summarize the relationships and functions between modules or modules, and abstracts the problem of the objective world into a process that can be processed by computers.
3The data processing method is different from the control program method. The object-oriented method encapsulates data and 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 method is to activate and run the program through "event-driven". The object-oriented process directly processes data through the program, and the processing results are displayed after the processing is completed. In terms of controlling the program, the program is called or returned to the program according to the design, and cannot be navigation. There is a relationship between the modules, between the control and the control, and the call and the call.
4The analysis design and encoding conversion methods are different. An analysis of an object-oriented approach throughout the software life cycle. In design and coding, it is a smooth process. From analysis to design and then to coding, it uses a consistent model to display, that is, it is a seamless connection. The object-oriented process method emphasizes the conversion between analytical design and coding according to rules, and the analysis and design and coding throughout the software life cycle is achieved.
What are the advantages of object-oriented development
1 Higher development efficiency. Using object-oriented development can abstract real things and directly map real practices into developed objects.
2 Ensure the robustness of the software. It is precisely because the object-oriented development method has high reusability. During the development process, existing code that has been tested in related fields has been reused. Therefore, it naturally plays a good role in promoting the robustness of the software.
3 Ensure high maintenance of the software. Due to the object-oriented development method, the code is readable very well. At the same time, the object-oriented design pattern makes the code structure clearer. At the same time, for the object-oriented development model, there are already many very mature design patterns. These design patterns can enable programs to only modify some modules when facing changes in demand, because it is more convenient to maintain.
What is the difference between this and super
In the JAVA language, this points 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 participates in the member variable, the member variable will be overwritten).
Super can be used to access methods or member variables of the parent class. When the method or member variable of the child class has the same name as the parent class, the method or member variable of the parent class will also be overwritten. If you want 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
Java language provides a method to get class name: getClass().getName(). Developers can call this method to get class name. However, for inheritance, the parent class's class name cannot be obtained by calling the getClass().getName() method of the parent class, for example:
Class A{}Public class Test extends A{public void test(){System.out.println(super.getClass().getName());}Public static void main(String [])args){New Test.test();}}The program run result is Test. The reason is that any class in the Java language inherits from the object class. The getClass method is defined as final native in the object class. Subclasses cannot override this method. Therefore, this.getClass() and super.getClass() finally call the getClass() method in the object class. The definition of the getClass() method in the object class is: return the runtime class of this object. The name code of the parent class can be obtained in the subclass through Java's reflection mechanism as follows:
Class A{}Public class Test extends A{public void test(){System.out.println(this.getClass().getSuperclass().getName());}Publci static void main(string[] args){New Test().test();}}What is the difference between combination and inheritance
Composition and inheritance are two ways of reusing code in object-oriented. Combination 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 based on the implementation of other classes. Both composition and inheritance allow setting of child objects in new classes, except that composition is displayed, while inheritance is implicit. There is a correspondence between combination and inheritance: the whole class in the composition corresponds to the subclass in inheritance, and the local class in the composition corresponds to the parent class in inheritance. When using it, follow the following two principles:
1 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 the 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 a "is-a" one, you can achieve the same purpose by implementing interfaces and combinations.
Since 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 too much inheritance is achieved, the content in a class will become bloated. Therefore, in the Java language, if you can use combinations, try not to use inheritance.
Thank you for reading, I hope it can help you. Thank you for your support for this site!