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 4

Published in the Random EN group
Hello everyone, today I continue to analyze 250+ interview questions for Java developer. Analysis of questions and answers from interviews for 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?

You can, but without the 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 finish the initialization and not fill in other fields (after all, 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 specific values, a constructor cannot use return to return a value because:
  • when declaring a constructor you won't have anything resembling a return type;
  • Typically, the constructor is called implicitly during instantiation;
  • A constructor is not a method: it is a separate mechanism whose sole purpose is to initialize instance variables, and the new operator is responsible for creating an object .
Analysis of questions and answers from interviews for Java developer.  Part 4 - 2

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

Constructors deal with exceptions in exactly 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 an inheritor constructor, we can expand the exception type. For example, IOException -> Exception (but not vice versa). As an example for throwing an exception by a constructor, let's take the Cat class . Let's say that when creating 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 specify it in the header as a possible thrown exception.

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

Speaking of the elements that make up the class header, let's look at a small diagram:
  • mandatory components will be in brackets <>
  • optional - in {}
{class access modifier}{class staticity}{class finality}{class abstraction} <class name>{inheritance from Parent class} {interface implementation} So, what we have: {class access modifier} - only the public modifiers and the missing access modifier, that is, default , are available for the class . {class static} - static is 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-inheritable (example from the box - String ). {class abstraction} - modifier - abstract , which indicates that this 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 the given 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, using both modifiers at the same time would be absurd, and the compiler will not allow us to do this. <class> is a required keyword that indicates a class declaration. <class name> is a simple class name, which is the identifier of a specific Java class. The fully qualified class name consists of the fully qualified package name + . + simple class name. {inheritance 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 inherits from Cat and implements the WildAnimal interface :
public final class Lion extends Cat implements WildAnimal
Analysis of questions and answers from interviews for Java developer.  Part 4 - 3

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

Again, when looking at the elements that make up a method header, consider a small diagram where:
  • mandatory components are in brackets <>
  • optional - in {}
{access modifier}{method static}{method abstraction}{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 . {method static} - static is a modifier that indicates that this method is static, that is, it is tied not to an object, but to a class. {method abstraction} is the abstract modifier , which indicates that there is no implementation (body) of the method. For correct operation, you also need an abstract modifier for the class in which the method is provided. 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 overriding the method in the descendant, and static methods are not overridden. {finality of the method} - 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 a different programming language. <return value> is the type of value that the method should return. If it should not return anything, void . <method name> is the name of the method, its identifier in the system. {method arguments} are the arguments (parameters) that the method takes: they are necessary to implement its functionality. {throwable exceptions} - throwsExceptionType - a list of checked exceptions that this method can throw. And as an example of a method header, I’ll give this:
public static void main(String[] args) throws IOException

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

I don’t 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 Java developer.  Part 4 - 4

34. When is the this keyword used?

In Java, this has two different meanings. 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 code readability and avoid ambiguity. For example, if the name of the internal class field and the method argument are the same:
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, like 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 successfully initialized. There are a couple of nuances:
  1. this() only works in the constructor.
  2. A reference to another constructor must be in the first line of the constructor block (body). Therefore, more than one (other) constructor of a given class cannot be called in one constructor.
Analysis of questions and answers from interviews for 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 ordinary and statistical initialization blocks. First, let's remember what initialization is. Initialization is creation, activation, preparation for work, determination of parameters. Bringing a program or component into a state of readiness for use. As you remember, during object creation, a class variable can be initialized directly upon declaration:
class Cat {
   private int age = 9;
   private  String name = "Tom";
Or set it externally via a 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. Typically, such blocks are used to perform some complex calculations that are necessary when loading a class. The results of these calculations can be specified as values ​​for variables. Also, in addition to regular initialization blocks, there are static ones, which 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 regular one is triggered when each object is initialized, then the static one will trigger 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. The same restrictions apply to a static block as to 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 Java developer.  Part 4 - 6Next, we can see the order of initialization of the class (together with its ancestor) for a better understanding of the moment when the initialization blocks are triggered.

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

When the Child class is loaded, the initialization order will be as follows:
  1. Static fields of the Parent class .
  2. Static initialization block for the Parent class .
  3. Static fields of the Сhild class .
  4. Static initialization block for the Child class .
  5. Non-static fields of the Parent class .
  6. Not a static initialization block for the Parent class .
  7. Constructor for the Parent class .
  8. Non-static fields of the Child class .
  9. Not a static initialization block for the Child class .
  10. Constructor of the Child class .
Analysis of questions and answers from interviews for Java developer.  Part 4 - 7Here's a short article that explains the initialization order in practice.

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

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

38. What associative connections between objects do you know?

Aggregation and composition are nothing more than 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 a 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 don’t care about the number of passengers (or whether there are any at all): the functionality of the Car class does not depend on this. Aggregation also implies that when an object is used by another object, the first one can be used in other objects. For example, the same student can be a member of both a knitting club and a music group of rockers, and at the same time go to a group of English learners. As you understand, aggregation is a looser associative relationship between classes. Analysis of questions and answers from interviews for Java developer.  Part 4 - 8Composition is an even more rigid relationship when an object is not only part of another object, but the work of the other object is very dependent on the first. For example, a car engine. Although the engine may exist without the car, it is useless outside of it. Well, a car cannot 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 cannot belong to someone else. If we return to our example, an engine can only belong to one car, but not to two or more at the same time. We’ll probably stop here today.Analysis of questions and answers from interviews for Java developer.  Part 4 - 9
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION