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

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

Published in the Random EN group
Hello! Just as it is impossible to learn to fly an airplane without special training, it is also impossible to become a Java developer without spending long hours studying the necessary theoretical basis. Today we will work on exactly this: we will continue to analyze 250+ interview questions for Java developers and, accordingly, 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 have a good understanding of the ins and outs 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 Java developer.  Part 3 - 1

20. What language elements are responsible for encapsulation?

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

21. Which language elements are responsible for inheritance?

Inheritance is a mechanism that allows you to create classes based on another class. In Java, the extends keyword is used 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 methods and variables of the Cat class , except static ones. Also, the language elements responsible for inheritance include super . This is a reference similar to this , but while this refers to the object on which it was called, super refers to the current parent object. Typically super is used:
  1. To call a superclass constructor: For example, the Cat class has an internal variable 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 access parent fields and methods: 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 access the age variable of the parent object from the Lion object , we need to do this through super :
super.name

22. Which language elements are responsible for polymorphism?

Polymorphism is the ability of an object of one signature to take many forms (multiple implementations). We can safely say that in Java the implements and extendsAnalysis of questions and answers from interviews for 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 remember what implementing implements looks like :
public class Cat implements Animal
And in the Cat class we must implement all the abstract methods presented in the Animal interface . The same goes for inheritance: in a descendant 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 descendants. 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 to make it easier to detect errors. With this annotation, you indicate to the compiler that you want to override/implement a superclass/interface method, and it will ensure that you do not 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 goal and a single purpose. That is, you should not create classes that do everything. In this case, you can reproduce the “Divine Object” antipattern. If you have a Cat object , it should contain methods that interact only with its internal functionality, and not business logic that is not relevant to this instance. For example, some kind of saving of objects of this type somewhere. This external functionality (relative to Cat ) needs to be transferred to other classes, some services whose task is to provide business logic for objects of this type. O - Open-closed principle - principle of openness/closedness. It means that software 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 , 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 or 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 interchangeable with any of its descendants, say Lion , without fundamentally changing the behavior. The general logic (behavior) remains the same, but the details of the implementation of this or that functionality change. I - Interface segregation principle - the principle of interface separation. This principle states that it is better to have many specialized (narrowly focused) interfaces than one universal one. For example, a user implements some interface, of which he only needs this 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 interface methods, nine of which are unnecessary for him! Instead, it is better to make ten different interfaces that can be implemented if necessary. Well, or not ten, but several, which will have methods that are closely related to the common purpose of the interface. D - Dependency Inversion Principle— the principle of dependency inversion. The principle states that modules at higher levels should not depend on modules at lower levels. 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 pass specific objects to this functionality, the classes of which implement the required interface. For example, if we have a Cat interface and some of its implementations, say, Lion and HomeCat , we build our interaction logic specifically with the Cat interface type , and only then 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 interaction between objects. It turns out that the program is like an anthill, where each ant is an object. Analysis of questions and answers from interviews for Java developer.  Part 3 - 3Objects are some grouped data that contain various methods (functions) to interact with this internal data. And classes are instructions, templates for creating objects. That is, there can be many objects constructed according to the same instruction, filled with different or identical data values. To 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 based on this drawing. Interfaces are analogues of classes with the difference that objects cannot be created using them. Their goal is to add an element of abstraction to Java. More precisely, to add flexibility in the relationships between classes and objects. By flexibility we mean the polymorphism and abstraction described earlier, which in turn open up many opportunities 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 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 specific 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 that POJOs can have methods with business logic and constructors of any kind. If you allow annotations that do not make changes to 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 JPA Entity entities and DTO objects deserialized from XML or JSON , the rules for which are specified in the annotations. It is also advisable to override equals and hashCode for POJO classes , as this may help them perform their role better. Example POJO class:
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 above the class itself or its components);
  • generics ;
  • inheritance from other classes ( extends ) or implementation from interfaces ( implements ).

27. Explain inheritance in Java. What are the benefits of using the super keyword?

Above I have 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, they just won’t have access to them from the heir (but if we, for example, have a private field and there are public or protected getters and setters for it, the field can be worked with 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 tied not 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 over them).
  8. Overridden methods in the descendant can be extended with an access modifier: private -> default -> protected -> public .
  9. Overridden methods in the descendant can narrow the exceptions that are written, for example: Exception -> IOException -> FileNotFoundException.
Analysis of questions and answers from interviews for 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 or the exceptions it throws. 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 that are thrown, is called the method contract . That's all for today. See you later!Analysis of questions and answers from interviews for Java developer.  Part 3 - 6
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION