Java Object-oriented interview highlights _java

Source: Internet
Author: User
Tags access properties anonymous constructor modifier static class

java object-oriented: here to organize the basic object-oriented knowledge, to help you learn to understand, I hope to help you, here is according to the company interview data collation related knowledge:

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

Overload is the meaning of overloading, override is the meaning of coverage, that is, rewriting. Overloaded overload means that there can be more than one method with the same name in the same class, but the argument lists of these methods are different (that is, the number or type of arguments is not the same).

overriding override means that a method in a subclass can be exactly the same as the name and parameters of a method in the parent class. When this method is called by an instance object created by a subclass, the defined method in the subclass is invoked, which overrides the exact same method defined in the parent class. This is also a manifestation of the polymorphism of object-oriented programming.

Override can be translated as overlay, literally knowing that it is overriding a method and rewriting it in order to achieve different roles. The most familiar overlay for us is the implementation of the interface method, in which the method is generally declared, and we need to implement all the methods of the interface declaration when we implement it. In addition to this typical usage, we may also overwrite methods in the parent class in the inheritance. The following points should be noted in the overlay:

1. The marking of the covering method must match the mark of the method covered, so as to reach the effect of coverage;
2. The return value of the overridden method must be consistent with the return of the overridden method;
3. The exception thrown by the overridden method must be the same as the exception thrown by the overridden method, or its subclass;
4, the overridden 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 of the same names, differentiating these methods by defining different input parameters, and then calling, the VM chooses the appropriate method to perform according to the different parameter styles. The following are some things to note when using overloads:

1. When using overloads, you can only pass different parameter styles. For example, different parameter types, different number of parameters, different order of parameters (of course, several parameter types within the same method must not be the same, for example, can be fun (int,float), but not fun (int,int));
2, can not be accessed by Access rights, return type, thrown by the exception to overload;
3, the method of the exception type and number does not affect the overload;
4. For inheritance, if a method is priavte in the parent class, then it cannot be overloaded in subclasses, and if defined, it simply defines a new method and does not achieve the overload effect.

If several overloaded methods have different argument lists, their return types can be different. If the argument list of two methods is exactly the same, it is not possible to implement overloaded overload by different return values. We can use contradiction 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 a variable that receives the return result, assuming that there are two identical names and parameter lists in the class. Simply because the return type is different, Java cannot determine which method the programmer is going to invoke, because it cannot be judged by the return type of the result.

Can the constructor constructor be override?

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

Does an interface inherit an interface? Does an abstract class implement (implements) interfaces? Can an abstract class inherit a specific class (concrete Class)? Can there be 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 an abstract class.

The only difference between an abstract class and a normal class is that you cannot create an instance object and allow an abstract method.

When writing the Clone () method, there is usually a line of code, what is it?

The Clone () method is a clone, is to copy the object, that is, there is already an object A, where a contains some valid values, but 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.

Copy: The ① Copy object returns a new object, not a reference. The difference between the ② copy object and the object returned with the new operator is that the copy already contains the original object's information, not the object's initial information

Clone has the default behavior, Super.clone (), because the member in the parent class is first copied into place, and then the member is copied.

What are the aspects of object-oriented features

The Object-oriented programming language has 4 main characteristics, such as encapsulation, inheritance, abstraction, polymorphism and so on.

1 package:

Encapsulation is to ensure that the software components have excellent modularity, the purpose of the package is to achieve the software components "high cohesion, low coupling" to prevent the program interdependence and the impact of the changes. In object-oriented programming languages, objects are the most basic unit of encapsulation, and object-oriented encapsulation is clearer and more powerful than the encapsulation of traditional languages. Object-oriented encapsulation is the encapsulation of the attributes and behavior of an object in a "module", a class in which attributes are defined by variables, and behavior is defined by methods, which directly access properties in the same object. In general, just remember to let variables and access to this variable together, the member variables in a class are all defined as private, only this class of their own methods can access these member variables, which basically implement the object encapsulation. Grasp a principle: The method of operation of the same thing and related methods in the same class, the method and its operation of the data in the same class.

2. Abstract:

Abstraction is to find similarities and commonalities of things, and then classify them as a class that takes into account similarities and commonalities of these things, and ignores those aspects unrelated to the current topic and goal, focusing on aspects related to the current goal. For example, to see an Ant and an elephant, you can imagine their similarities, and that is abstraction. Abstraction consists of two aspects of behavioral abstraction and State abstraction. For example, define a person class, as follows:

Class person{ 
String name; 
int age; 
} 

A person is a very complex thing, there are many aspects, but because the current system only need to understand the name and age, so the class defined above contains only the names and age of the two attributes, this is a draw, using abstractions to avoid the consideration of some of the details unrelated to the goal.

3. Inheritance:

When defining and implementing a class, it can be done on the basis of an already existing class, with the content defined by the existing class as its own content, adding several new content, or modifying the original method to make it more suitable for special needs, which is inheritance. Inheritance is the mechanism by which subclasses automatically share parent data and methods, which is a relationship between classes, which improves the reusability and scalability of the software.

4 polymorphic:

Polymorphism refers to the specific type that the reference variable defined in the program and the method call issued through the reference variable are not determined programmatically. It is only when the program is running that a reference variable will point to the instance object of which class, and the method called by the reference variable is the method implemented in which class. Must be determined by the time the program is run. Because the specific class is determined when the program is run, in this way, without modifying the source code, the reference variable can be bound to a variety of different class implementations, which causes the specific method of the reference call to change, that is, without modifying the program code can change the code that the program is bound to, so that the program can select multiple running states, This is polymorphism. Polymorphism enhances the flexibility and scalability of the software. For example, the Userdao in the following code is an interface that defines a reference variable Userdao the instance object to which the Daofactory.getdao () is returned at execution time, sometimes pointing to the Userjdbcdao implementation. Sometimes point to userhibernatedao this implementation, so that without modifying the source code, you can change the Userdao point to the specific class implementation, resulting in the Userdao.insertuser () method invocation of the specific code also changes, That is, sometimes the Userjdbcdao Insertuser method is invoked, and sometimes the Insertuser method of Userhibernatedao is invoked:

Userdao Userdao = Daofactory.getdao (); Userdao.insertuser (user);

What is the mechanism for implementing polymorphism in Java?

A reference variable that is defined by a parent class or interface can point to a subclass or an instance object of a specific implementation class. The method invoked by the program is dynamically bound at run time, which is the method of referring to the specific instance object that the variable refers to, that is, the method of the object being run in memory, not the method defined in the type of the variable.

What is the difference between abstract class and interface?

Class that contains the abstract modifier is an abstract class, an instance object that the abstract class cannot create. A class that contains an abstract method must be defined as a method in the abstract Class,abstract class classes that does not have to be abstract. Abstract methods defined in the abstract class class must be implemented in a specific (concrete) subclass, so there can be no abstract constructor or abstract static methods. If the subclass does not implement all abstract methods in the abstract parent class, then the subclass must also be defined as an abstract type.
An interface (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 public static final.

The grammatical differences between the two:

1. Abstract classes can have construction methods, and interfaces cannot have construction methods.
2. An abstract class can have ordinary member variables, there are no ordinary member variables in the interface
3. Abstract classes can contain generic methods that are not abstract, and all methods in an interface must be abstract and not have a generic method that is not abstract.
4. The access type of an abstract method in an abstract class can be public,protected and (the default type, although not an error in eclipse, but should not), the abstract method in the interface can only be of public type, and the default is the public abstract type.
5. The abstract class can contain static methods, and the interface cannot contain static methods
6. Abstract classes and interfaces can contain static member variables, and the access type of static member variables in an abstract class can be arbitrary, but the variables defined in the interface can only be public static final types, and the default is the public static final type.
7. A class can implement multiple interfaces, but can inherit only one abstract class.

The difference between the two applications:

Interfaces are more useful in system architecture design methods, primarily for defining communication contracts between modules. and abstract classes play a role in code implementation, you can implement code reuse, for example, template method design patterns are a typical application of abstract classes, assuming that all servlet classes for a project have the same way of determining permissions, logging access logs, and handling exceptions, you can define an abstract base class, Let all the servlet inherit this abstract base class, in the abstract base class service method to complete the right to judge, record access log and handling the exception code, in each subclass is just complete their own business logic code, pseudocode as follows:

Public abstract class Baseservlet extends httpservlet{public
    final void service (HttpServletRequest request, HttpServletResponse response) throws  
    ioexcetion,servletexception {
   record access log
     for permission to determine
      if (with permissions) {
  try{
    Doservice (request,response);
}
  catch (Excetpion e) {
      record exception information
  }
}
    } 
    protected abstract void Doservice (HttpServletRequest Request, HttpServletResponse response) throws 
   ioexcetion,servletexception;//note access rights are defined as protected, professional and rigorous, Because it is
                 the public
class MyServlet1 extends Baseservlet
{protected void Doservice that is specifically used for subclasses
( HttpServletRequest request, HttpServletResponse response) throws Ioexcetion,servletexception
    {
      Specific business logic code that this servlet handles only
    } 



A section of code in the middle of the parent class is not sure, leaving the subclass to dry, using the template method to design the pattern.

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

The method of abstract cannot be static, because abstract methods are implemented by the quilt class, and static is not related to subclasses!

Native method means that this method is to be implemented in another platform-dependent programming language, and there is no problem of quilt implementation, so it cannot be abstract and can not be mixed with abstract. For example, the Fileoutputsteam class wants hardware to deal with, and the underlying implementation is implemented by operating system-related APIs, for example, in the language of Windows C, so view the source code of the JDK, You can see that the FileOutputStream open method is defined as follows: private native void Open (String name) throws FileNotFoundException;

If we want to use Java to invoke other people to write C language functions, we can not directly call, we need to write a C-language function in accordance with the requirements of Java, and our C language function to call someone else's C language function. Since our C-language functions are written in Java's requirements, we can use the C language function with Java docking, Java side of the docking way is defined with our C function corresponding to the method, Java corresponding method does not need to write specific code, but need to declare native in front.

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

What is an inner class? Static Nested class differs from Inner class.

An inner class is a class defined within a class, static members cannot be defined in internal classes, static members are not attributes of objects, just to find a place to shelter, so they need to be placed in a class, the inner class can directly access the member variables in the outer class, and the inner class can be defined outside the method of the outer class. It can also be defined in the method body of the external class, as follows:

public class Outer
{
    int out_x = 0;
    public void Method ()
    {
      Inner1 inner1 = new Inner1 ();
      The public class Inner2  //internal class {Public methods
        ()
        {
          out_x = 3;
        }
      }
      defined inside the method body Inner2 inner2 = new Inner2 ();
    }

    public class Inner1  //internal class
    {
    }

} defined outside the method body

The access type of an inner class defined outside the method body can be public,protecte, the default private, etc. 4 types, as if the member variable defined in the class has 4 types of access, which determines whether the definition of the inner class is visible to other classes; We can also create an instance object of an inner class outside, create an instance object of an inner class, create an instance object of the outer class first, 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 is no access type modifier in front of the inner class defined within the method, just as the local variable is defined in the method, but the final or abstract modifier can be used before the inner class. This inner class cannot reference this inner class for other classes that are invisible to other classes, but an instance object created by such an inner class can be passed to other class accesses. This inner class must be defined first, and then used, that is, the definition code for the inner class must appear before the class is used, as is the case with the local variables in the method that must be defined before they are used. This inner class can access local variables in the method body, but the local variable must be previously added with the final modifier.

Within the method body you can also create an anonymous inner class that defines a subclass of an interface or class, and also creates an instance object of that subclass without having to define a name for that subclass:

public class Outer
{public
    void start ()
    {
      new Thread (
      new runable () {public
          void Run () {};
    }) . Start ();
  }
}

Finally, the inner class that is defined outside the method can be preceded by a static keyword, which becomes the static Nested class, which no longer has the characteristics of the inner class, all of which, in narrow sense, is not an inner class. The Static Nested class has nothing to do with the behavior and functionality of ordinary classes at run time, except that there are some differences in the syntax of programming references, which can be defined as public, protected, default, private, and many other types, The normal class can only be defined as public and default in both of these types. On the outside reference to the static Nested class has the name "external class name. Internal class name." You can create a static Nested class directly outside without creating an instance object of an external class, for example, assuming that inner is a static Nested class defined in the outer class, you can use the following statement to create a inner class:

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

Because the static Nested class does not depend on an instance object of an external class, the static Nested class can access the non-static member variables of the outer class. When accessing the static Nested class in an external class, you can use the name of the static Nested class directly, without having to add the name of the external classes, and you can also refer directly to the static member variables of the outer class in the static Nested class. You do not need to add the name of the external class.
The inner class that is defined in the static method is also the static Nested class, which cannot be preceded by a static keyword, which is similar to the Nested class in a static method that is applied to the internal classes in the common method. It can also access local variables in static methods in addition to direct access to static member variables in the external class, but the local variable must be previously added with the final modifier.

Can an inner class reference a member of its containing class? Are there any restrictions?

It's perfectly OK. If it is not a static internal class, there is no limit!

If you treat a static nested class as a special case of an inner class, you cannot access the normal member variables of the outer class in this situation, but only the static members in the external class, for example, the following code:

Class Outer
{
  static int x;
  Static class Inner
  {
    void Test ()
    {
      syso (x)
}}}}

Anonymous Inner Class (anonymous inner Class) can extends (inherit) other classes, 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, call the GetClass (). GetName () method directly, returning the test class name, and because GetClass () is defined as final in the object class, the subclass cannot overwrite the method, so call GetClass in the test method ( The. GetName () method, in effect, is to invoke the GetClass () method inherited from the parent class, which is equivalent to calling Super.getclass (). GetName () method, so Super.getclass (). GetName () The method should also return test. If you want the name of the parent class, you should use the following code:

GetClass (). Getsuperclass (). GetName ();

What is the difference between object-oriented and process orientation

1 starting point is different. Object-oriented approach is to deal with the problem of the objective world in a way that accords with conventional thinking. Emphasis is placed on the interface between object and object directly to the problem domain. The process-oriented approach emphasizes the abstraction and modularization of process, which constructs or deals with the objective world problem.

2 different levels of logic, object-oriented method is using computer logic to simulate the physical existence of the objective world, with the collection of objects as the basic unit to deal with the problem, as far as possible to the computer world as the objective world closer, so that the treatment of problems more direct and clear directly, Object-oriented approach is to embody the inheritance and development between classes with class hierarchy. and object-oriented process method to deal with the basic unit of the problem so that the module can be clearly and accurately express the process, using the hierarchical structure of modules to generalize the relationship between modules or modules, the problem of the objective world into the process of computer can be processed

3 Data processing mode is different from control procedure. The Object-oriented method encapsulates the data with the corresponding code as a whole, in principle other objects cannot modify their data directly, that is, the modification of the object can only be done by its own member function, and the program is activated and run by "event-driven". and object-oriented process is directly through the program to deal with data, processing after the display of processing results, in the control program is based on the design call or return program, can not be guided by the navigation, between the control and control of the modules, the relationship between the call and called.

4 The analysis design is different from the coding conversion mode. The object-oriented approach runs through the analysis of software life cycle. Design and coding, is a smooth process, from analysis to design and coding is the use of a consistent model of the show, that is, to achieve a seamless connection. The object-oriented process method emphasizes the analysis design and the code conversion between the codes, which runs through the analysis, design and coding of the software life cycle, and realizes a kind of seam connection.

What are the advantages of object-oriented development methods

1 high development efficiency. The object-oriented development can be used to abstract realistic things, which can be directly mapped into the object of development.

2 to ensure the robustness of the software, it is because the object-oriented development method has a high reusability, in the development process can reuse existing and in the relevant field after long-term testing of the code, therefore, the natural robustness of the software to play a good role in promoting.

3 guarantee the high maintenance of the software. Because of the object-oriented development method, the code readability is very good, while the object-oriented design pattern makes the code structure clearer, at the same time, for the object-oriented development model, there are many very mature design patterns, these design patterns can make the program in the face of changes in requirements, Only need to modify part of the module to meet the requirements, because maintenance more convenient.

What's the difference between this and super?

In the Java language, this is a point to the current instance object, and one of his very important roles is to differentiate between the member variables of the object and the parameters of the method (the member variable is overwritten when the name of the form participating member variable of a method is the same).
Super can be used to access the method or member variables of the parent class. When a subclass's method or member variable has the same name as the parent class, the parent class's method or member variable is overwritten, and the method or member variable to access the parent class can only be accessed through the Super keyword

How to get the class name of the parent class

The Java language provides a way to get the class name: GetClass (). GetName (), which developers can call to get the class name. For inheritance, however, you cannot get the class name of the parent class 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 result of the program running is test. The reason is that any class in the Java language inherits from the object class, and the GetClass method is defined in the object class as final native, and subclasses cannot override the method. So This.getclass () and Super.getclass () end up calling the GetClass () method in the object class. The GetClass () method in the object class is explained by returning the Run-time class for this object. You can get the name code of a parent class in a subclass from the Java 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 composition and inheritance

Combination and inheritance are two ways of reusing code in an object-oriented way. A combination is an object that creates an existing class inside a new class, reusing the functionality of an existing class. Inheritance is one of the main object-oriented features that allow designers to define the implementation of a class based on the implementation of other classes. Combination and inheritance allow child objects to be set in the new class, except that the combination is displayed and the inheritance is implicit. There is a correspondence between composition and inheritance: The overall class in the composition corresponds to the subclasses in the inheritance, and the local class in the combination corresponds to the parent class in the inheritance. Follow these two principles when using:

1 Unless there is a "is-a" relationship between the two classes, inheritance is not easy to use because excessive use of inheritance destroys the maintainability of the code and affects all subclasses that inherit from him when the parent class is modified.

2, do not use inheritance just to achieve polymorphism, if the class is not a "is-a" relationship, you can achieve the same goal by implementing the interface and composition.
Because the Java language supports only single inheritance, if you want to inherit two or more classes at the same time, you cannot directly implement them in Java, and in the Java language, if you inherit too much, you can make the contents of one class bloated, so in the Java language, you use a combination to try not to use inheritance.

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.