JavaRush /Java Blog /Random EN /Analysis of questions and answers from interviews for a J...

Analysis of questions and answers from interviews for a Java developer. Part 3

Published in the Random EN group
Hello! Just as it is impossible to learn how to fly an airplane without special training, it is impossible to become a Java developer without spending long hours studying the necessary theoretical base. Today we will work on exactly this: we will continue to analyze 250+ interview questions for Java developers and, accordingly, the answers to them. Here are the first and second parts of the analysis. Yes, of course, you can become a good Java developer without all these questions. However, if you are well versed in all the intricacies of the Java language, it will give you an advantage, making you a more desirable candidate in the eyes of your future employer.Analysis of questions and answers from interviews for a Java developer.  Part 3 - 1

20. What language elements are responsible for encapsulation?

As we remember, encapsulation is the hiding of the implementation details of a class. That is, when our class is used from the outside, the internal stuffing and logic are not obvious. And what elements of the language are responsible for this? Naturally, access modifiers ! What we need to hide, we mark with the private modifier . For example, private class fields or some internal methods that help implement some internal functionality. And to what we want to provide external access, we add the public access modifier . For example, a method responsible for providing some functionality (inside which many private methods can be used) or the same getters and setters for accessing private class fields. Oh yes, we still have modifiersdefault and protected , which can be used for more flexible and specific customization of access to selected parts of the class.

21. What language elements are responsible for inheritance?

Inheritance is a mechanism that allows you to create classes based on another class. Java uses the extends keyword for this purpose . For example, we have a certain class Cat , and we want to create its successor - Lion . In code it will look something like this:
public class Lion extends Cat
And this means that the Lion class inherits all the methods and variables of the Cat class , except for the static ones. Also, the elements of the language responsible for inheritance include super . It is a reference similar to this , but if this refers to the object on which it was called, then super refers to the current parent object. Typically super is used:
  1. To call the superclass constructor: for example, the Cat class has an internal variable called name that needs to be initialized in the constructor. In the Lion class constructor , it would look like this:

    public Lion(final String name) {
       super(name);
    }
  2. To refer to the fields and methods of the parent: for example, in the Cat class , we have an initialized age field :

    public class Cat {
       int age = 10;
At the same time, we have the same initialized field in Lion :
public class Lion extends Cat {
   int age = 15;
And if we want to refer from the Lion object to the parent object's age variable , we need to do this through super :
super.name

22. What elements of the language are responsible for polymorphism?

Polymorphism is the ability of an object of one signature to take many forms (many implementations). We can safely say that in Java, the implements and extendsAnalysis of questions and answers from interviews for a Java developer.  Part 3 - 2 keywords are responsible for polymorphism . implements - when we create our interface, we implement one of its possible forms in some class, but it is not the only form, is it? Let's recap what implements looks like :
public class Cat implements Animal
And in the Cat class, we must implement all the abstract methods provided in the Animal interface . Inheritance is the same: in a derived class, we can override an already existing implementation of a method. For example: several descendants -> several different overrides of the same method. Well, either the superclass was abstract and it has a certain method that needs to be implemented in a special way for each of its heirs. That is, we can say that the method will take many forms. Also, the @Override annotation can help us with this., which is placed above the implemented methods and indicates that we want to implement or override (if the implementation already exists in the superclass) one or another method of the superclass or interface. It is optional and is used for easier error detection. With this annotation, you show the compiler that you want to override/implement the superclass/interface method, and it will make sure you don't make mistakes in the method signature.

23. What is SOLID? Give examples

SOLID is an acronym for the five basic design principles for OOP, coined by Robert Martin. S - Single-responsibility principle - the principle of single responsibility, which states that a class should have only one purpose and a single purpose. That is, you should not create classes that do everything. In this case, the anti-pattern “God Object” can be reproduced. If you have a Cat object , it should contain methods that interact only with its internal functionality, and not business logic that is not related to this instance. For example, some kind of saving objects of this type somewhere. This external functionality (relative to Cat), you need to move to other classes, some services whose task is to provide business logic for objects of this type. O - Open-closed principle - the principle of openness / closeness. It means that program entities (classes, interfaces) should be open for extension, but closed for modification. For example, we needed functionality similar to the functionality of the already existing Cat class , but slightly different. Instead of changing the functionality of the Cat class , while breaking the places where it is already used, we use inheritance or composition . As a result, we achieved our goal with the modified functionality of the Cat class , but at the same time we did not change it and did not break anything. L - Liskov substitution principle - Barbara Liskov's substitution principle. The principle states that a function that uses a base type should be able to use subtypes of the base type without knowing it. For example, our Cat class should be replaceable by any of its descendants, say Lion , without drastically changing the behavior. The general logic (behavior) remains the same, but the details of the implementation of a particular functionality change. I—Interface segregation principle- the principle of separation of the interface. This principle says that it is better to have many specialized (narrowly targeted) interfaces than one universal one. For example, a user implements some interface, from which he needs only one method, but this interface has nine more methods that have nothing to do with the logic of the desired method. In this case, the user will need to implement ten methods of the interface, nine of which are superfluous for him! Instead, it's better to make ten different interfaces that can be implemented as needed. Well, or not ten, but several, which will have methods that are closely related to the single purpose of the interface. D - Dependency Inversion Principle— the principle of dependency inversion. The principle says that upper-level modules should not depend on lower-level modules. This principle is also described as “abstraction should not depend on details, details should depend on abstraction.” That is, we must build our logic by referring to interfaces, and only then transfer specific objects to this functionality, the classes of which implement the necessary interface. For example, if we have the Cat interface and some of its implementations, say, Lion and HomeCat , we build our interaction logic with the Cat interface type , and only then we substitute a specific implementation of Lion or HomeCat , but not vice versa.

24. What is a class, object, interface?

As we remember, Java is an OOP language. That is, Java programs are built on the interaction between objects. It turns out that the program is such an anthill, where each ant is an object. Analysis of questions and answers from interviews for a Java developer.  Part 3 - 3Objects are some grouped data that contain various methods (functions) for interacting with this internal data. And classes are instructions, templates for creating objects. That is, there can be many objects built according to the same instruction, filled with different or identical data values. If we give an example from life, we can say that a class is a drawing of a building, and an object is a specifically created building according to this drawing. Interfacesare analogs of classes with the difference that objects cannot be created from them. Their goal is to add an element of abstraction to Java. More precisely, add flexibility in the relationship between classes and objects. By flexibility we mean the previously described polymorphism and abstraction, which in turn open up many possibilities for building the internal architecture of the application.

25. What is a POJO class? Give an example of such a class

Analysis of questions and answers from interviews for a Java developer.  Part 3 - 4POJO - Plain Old Java Object - a good old Java object: a simple object of a class that is not inherited from any specific class and does not implement any service interfaces beyond those needed for the business model. In other words , a POJO class is just a class with no special requirements. The only requirement is the absence of various bells and whistles tied to a particular framework. As a rule, such classes do not inherit from other classes (except for POJO classes from the same package), do not implement interfaces - sometimes an exception is made for marker interfaces from the standard library such as Serializable or Cloneable - do not use annotations and do not depend on third-party libraries. But I note thatPOJO can be both methods with business logic, and arbitrary constructors. If you allow annotations that do not change the semantics of the class (without which the purpose of the object and the logic of its operation will not change), POJOs can also include Entity JPA entities and DTO objects deserialized from XML or JSON , the rules for which are specified in the annotations. It is also desirable for POJO classes to override equals and hashCode , because this can help them fulfill their role better. POJO class example :
public class User {
   private Long id;
   private String firstName;
   private String lastName;
   private Long age;

   public User(final Long id, final String firstName, final String lastName, final long age) {
       this.id = id;
       this.firstName = firstName;
       this.lastName = lastName;
       this.age = age;
   }

   public Long getId() {
       return this.id;
   }

   public String getFirstName() {
       return this.firstName;
   }

   public String getLastName() {
       return this.lastName;
   }

   public Long getAge() {
       return this.age;
   }

   @Override
   public boolean equals(final Object o) {
       if (this == o) return true;
       if (o == null || this.getClass() != o.getClass()) return false;
       final User user = (User) o;
       return Objects.equals(this.id, user.id) &&
               Objects.equals(this.firstName, user.firstName) &&
               Objects.equals(this.lastName, user.lastName) &&
               Objects.equals(this.age, user.age);
   }

   @Override
   public int hashCode() {
       return Objects.hash(this.id, this.firstName, this.lastName, this.age);
   }
}

26. What elements can a class contain?

The class may contain the following elements:
  • class fields;
  • static class fields;
  • initialization block;
  • static initialization block;
  • constructors (empty is always defined by default);
  • methods;
  • static methods;
  • various annotations (which can hang over the class itself or its components);
  • generics ;
  • inheritance from other classes ( extends ) or implementation from interfaces ( implements ).

27. Tell us about inheritance in Java. What are the specifics of using the super keyword?

Above, I already talked about inheritance and the super keyword in Java. Let me mention a few more important points:
  1. It is possible to inherit only one class: there is no multiple inheritance in Java (but with the advent of default methods in Java 8, this statement will become very controversial).
  2. Private methods and fields are also inherited, it’s just that they will not be accessible from the heir (but if, for example, we have a private field and it has public or protected getters and setters, you can work with the field through them).
  3. final classes are not inherited.
  4. final methods are not overridden (but they can be inherited and overloaded).
  5. static methods and variables are not inherited (since they are not bound to objects, but to classes).
  6. When inheriting from abstract classes, the implementation of their abstract methods is required, or the current class must also be declared abstract.
  7. If there are non-default constructors in the parent, they must be overridden in the child class (but @Override is not written above them).
  8. Overridden methods in a descendant can be extended with an access modifier: private -> default -> protected -> public .
  9. Overridden methods in a descendant can narrow down the exceptions they write, for example: Exception -> IOException -> FileNotFoundException.
Analysis of questions and answers from interviews for a Java developer.  Part 3 - 5

28. What is a method signature? Give examples of correct and incorrect signatures

The signature of a method is the name of the method plus the types of the incoming parameters (and the order of the parameters matters). The method signature does not include the return value, as well as the exceptions it throws. An example of a correct signature:
doSomething(int, double, double)
An example of an incorrect signature:
void doSomething(int firstArg, int secondArg) throws Exception
The method signature, combined with the return type and the list of exceptions thrown, is called the method contract . That's all for today. see you later!Analysis of questions and answers from interviews for a Java developer.  Part 3 - 6Analysis of questions and answers from interviews for a Java developer.  Part 3 - 7
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION