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 4

Published in the Random EN group
Hello everyone, today I continue to analyze 250+ interview questions for a Java developer. Analysis of questions and answers from interviews for a Java developer.  Part 4 - 1Previous parts of the analysis: first , second , third . So let's continue.

29. Is it possible to use return in a constructor?

Yes, but without a return value to the right of return . That is, you can use return; as an auxiliary construction during calculations in the constructor in order to urgently finish (interrupt) the execution of further code and complete the initialization of the object. For example, we have a class Cat , and if Cat is homeless — isHomeless = true , we need to complete the initialization and not fill in other fields (because they are unknown to us, since the cat is homeless):
public Cat(int age, String name, boolean isHomeless) {
   if (isHomeless){
       this.isHomeless = isHomeless;
       return;
   }
   this.isHomeless = isHomeless;
   this.age = age;
   this.name = name;
}
But when it comes to concrete values, a constructor cannot use return to return a value, because:
  • when declaring a constructor, you won't have anything that looks like a return type;
  • typically, a constructor is implicitly called at instantiation time;
  • a constructor is not a method: it is a separate mechanism whose sole purpose is to initialize instance variables, namely the new operator is responsible for creating an object .
Analysis of questions and answers from interviews for a Java developer.  Part 4 - 2

30. Is it possible to throw an exception from a constructor?

Constructors work with exceptions in the same way as methods. And if methods allow us to throw exceptions by writing throws <ExceptionType> in the method header , then the constructor allows us to do this, and also when inheriting and defining a successor constructor, we can expand the exception type. For example, IOException -> Exception (but not vice versa). Let's take the Cat class as an example for throwing an exception by a constructor . Let's say when we create it, we want to enter the name and age from the console:
public Cat() throws IOException {
   BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
   this.name = reader.readLine();
   this.age = Integer.parseInt(reader.readLine());
}
Since reader.readLine() throws an IOException, we include it in the header as a possible exception to be thrown.

31. What elements does the class header consist of? Write an example

Speaking of the elements that make up the class header, consider a small diagram:
  • required components will be in brackets <>
  • optional - in {}
{class access modifier}{class static}{class finality}{class abstractness} <class name>{inheritance from Parent class} {implementation of interfaces} So, what we have: {class access modifier} - only public modifiers and the missing access modifier, that is, default are available for the class . {class static} - static - a modifier that indicates that this class is static, applicable only to inner classes (classes inside other classes). {class finality} - as we remember, this is the final modifier , in the presence of which the class becomes non-inherited (an example out of the box is String ). {class abstractness} - modifier - abstract, which indicates that the given class may have unimplemented methods. This modifier conflicts with the final modifier , that is, only one of them can be in the class header, since the abstract modifier implies that this class will be inherited and its abstract parts will be implemented. And final indicates that this is the final (final) version of the class, and it cannot be inherited. Actually, the simultaneous use of both modifiers will be absurd, and the compiler will not let us do this. <class> is a required keyword that points to a class declaration. <class name>is a simple class name that is an identifier for a specific Java class. The fully qualified class name consists of the fully qualified package name + . + simple class name. {inheriting from Parent class} - specifying the parent class (if any) using the extends keyword . For example, .. extends ParentClass . {interface implementation} - specifying the interfaces that this class implements (if any) using the implements keyword . For example: ... implements FirstInterface, SecondInterface ... Well, as an example of a class header, consider the header of the Lion class , which is inherited from Catand implements the WildAnimal interface :
public final class Lion extends Cat implements WildAnimal
Analysis of questions and answers from interviews for a Java developer.  Part 4 - 3

32. What elements does the method header consist of? Write an example

Again, when considering the elements that make up the method header, consider a small diagram in which:
  • mandatory components - in brackets <>
  • optional - in {}
{access modifier}{class static}{method abstractness}{method finality}{synchronization modifier} {native modifier}<return value><method name> <(> {method arguments} <}>{thrown exceptions} {access modifier } — all access modifiers are available for the method — public , protected , default , private {class static}static — modifier that indicates that this method is static, that is, it is bound not to an object, but to a class { method abstractness} — modifier abstract, which indicates that there is no implementation (body) of the method. For correct work, the abstract modifier is also needed for the class in which the method is given. As in the class header, this modifier conflicts with the final modifier , but in addition to it, it also conflicts with the static modifier , because An abstract method implies that the method is overridden in the descendant, while static methods are not overridden. {method finality} - final - a modifier indicating that this method cannot be overridden. {synchronization modifier} - synchronized- a modifier that means that this method is protected from simultaneous access to it from different threads. If the method is not static, it closes on the object's this mutex. If the method is static, it closes on the mutex of the current class. {native modifier} - native - this modifier indicates that the method is written in another programming language. <return value> is the type of value that the method should return. If it should not return anything - void . <method name> — method name, its identifier in the system. {method arguments} — arguments (parameters) that the method takes: they are necessary to implement its functionality. {thrown exceptions} - throws ExceptionType - an enumeration of the checked exceptions that this method can throw. And as an example of a method header, I will give this one:
public static void main(String[] args) throws IOException

33. Create a default constructor in the child object if it is not defined in the base object (but another constructor is defined)

I do not fully understand the question itself, but perhaps it means that, for example, in the parent we have some custom constructor:
public Cat(int age, String name) {
   this.age = age;
   this.name = name;
}
Therefore, in the ancestor class, we definitely need to define a constructor that will fill (call) the parent constructor:
public  class Lion extends Cat {

   public Lion(int age, String name) {
       super(age, name);
   }
}
Analysis of questions and answers from interviews for a Java developer.  Part 4 - 4

34. When is the this keyword used?

In Java, this is used in two different ways. 1. As a reference to the current object, like this.age = 9 . That is, this refers to the object on which it was called and to which the code using this refers . The main function is to increase the readability of the code and avoid ambiguity. For example, with the same name of the internal class field and method argument:
public void setName(String name) {
   this.name = name;
}
That is, this.name is a field of the object name is a method argument. The this reference cannot be used in static methods. 2. this can be used in a constructor in the form of a method call, such as this(value) . In this case, it will be a call to another constructor of the same class. In short, you can call two constructors at once when creating an object:
public Cat(int age, String name) {
   this(name);
   this.age = age;
}

public Cat(String name) {
   this.name = name;
}
When a Cat object is created and the first constructor is called, both fields of the object will be called and initialized successfully. There are a couple of nuances:
  1. this() only works in a constructor.
  2. A reference to another constructor must be in the first line of the block (body) of the constructor. Therefore, in one constructor, more than one (another) constructor of this class cannot be called.
Analysis of questions and answers from interviews for a Java developer.  Part 4 - 5More examples are in this article .

35. What is an initializer?

As far as I understand, in this question we are talking about regular and statistical initialization blocks. First, let's remember what initialization is. Initialization is creation, activation, preparation for work, definition of parameters. Bringing a program or component to a state of readiness for use. As you remember, during the creation of an object, a class variable can be initialized directly when it is declared:
class Cat {
   private int age = 9;
   private  String name = "Tom";
Or set from outside through the constructor:
class Cat {
   private int age;
   private  String name;

   public Cat(int age, String name) {
       this.age = age;
       this.name = name;
   }
But there is another way: to set an internal object variable through an initialization block, which looks like curly braces { } inside the class, without a name (like a method or constructor):
class Cat {
   private int age;
   private  String name;

   {
       age = 10;
       name = "Tom";
   }
That is, an initialization block is a piece of code that is loaded when an object is created. As a rule, such blocks are used to perform some complex calculations that are necessary when loading a class. The results of these calculations can be given as values ​​for variables. Also, in addition to the usual initialization blocks, there are static ones that look the same, but have the static keyword before the curly brace :
class Cat {
   private static int age;
   private static String name;

   static{
       age = 10;
       name = "Tom";
   }
This block is exactly the same as the previous one. But if the usual one is triggered when each object is initialized, then the static one will work only once, when the class is loaded. In such a block, as a rule, some complex calculations are also performed for the subsequent initialization of static class variables. For a static block, the same restrictions apply as for static methods: it cannot use non-static data, as well as a reference to the current object - this . Analysis of questions and answers from interviews for a Java developer.  Part 4 - 6Next, we can see the order of initialization of the class (along with its ancestor) for a better understanding of the moment when initialization blocks fire.

36. To inherit a class public class Child extends Parent, write the order of object initialization

When loading the Child class, there will be the following initialization order:
  1. Static fields of the Parent class .
  2. Static initialization block of the Parent class .
  3. Static fields of the Child class .
  4. The static initialization block of the Child class .
  5. Non-static fields of the Parent class .
  6. Not a static initialization block of the Parent class .
  7. The constructor of the Parent class .
  8. Non-static fields of Child class .
  9. Not a static initialization block of the Child class .
  10. Child class constructor .
Analysis of questions and answers from interviews for a Java developer.  Part 4 - 7Here is a short article that explains the order of initialization in practice.

37. What kind of relationships do you know between classes (objects)?

There are two kinds of relationships between classes in Java:
  • IS-A relationship
The IS-A principle in OOP is based on the inheritance of classes or the implementation of interfaces. For example, if the class Lion inherits Cat , we say that Lion is Cat :
Lion IS-A Cat
(but not every Cat is a Lion ) Exactly the same situation with interfaces. If the Lion class implements the WildAnimal interface , then they are also in a relationship:
Lion IS-A WildAnimal
  • HAS-A relationship
This type of relationship is based on the use of classes by other classes, also called “association”. An association is one class that refers to another class (or even to each other). For example, the Car class can refer to the Passenger class , and this would be a relationship:
Car HAS-A Passenger
And vice versa: if Passenger has a reference to Car , then this will be a relation:
Passenger HAS-A Car

38. What associative links between objects do you know?

Aggregation and composition are nothing but special cases of association. Aggregation is a relationship where one object is part of another. For example, a passenger may be in a car. Also, there may be several passengers or not at all (if we are talking about Tesla, then the driver is not required). For example:
public class Car {
   private List passengers = new ArrayList<>();

 void setPassenger(Passenger passenger) {
     passengers.add(passenger);
 }

   void move() {
       for (Passenger passenger : passengers) {
           System.out.println("Перевозка пассажира - " + passenger.toString());
       }
       passengers.clear();
   }
}
That is, we do not care about the number of passengers (and whether there are any at all): the functionality of the Car class does not depend on this. Also, aggregation implies that when an object is used by another object, the first one can be used in other objects. For example, the same student may be in both a knitting group and a rock band, and still be in an English learner group. As you understand, aggregation is a looser associative relationship of classes. Analysis of questions and answers from interviews for a Java developer.  Part 4 - 8Composition is an even more rigid relationship when an object is not only a part of another object, but the work of another object is very dependent on the first one. For example, a car engine. Although the engine may be without a car, it is useless outside of it. Well, the car can not work without an engine:
public class Car {
   private Engine engine;

   public Car(Engine engine) {
       this.engine = engine;
   }

   void startMoving() {
       engine.start();
           ...
   }
Composition also implies that when an object is used by another object, the first object cannot belong to anyone else. To return to our example, an engine can only belong to one car, but not two or more at the same time. On this today, perhaps, we will make a stop.Analysis of questions and answers from interviews for a Java developer.  Part 4 - 9Analysis of questions and answers from interviews for a Java developer.  Part 4 - 10
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION