Hello everyone, today I continue to analyze 250+ interview questions for a Java developer. Previous parts of the analysis: first , second , third . So let's continue.
<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 :
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 .
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 {}
public final class Lion extends Cat implements WildAnimal
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 {}
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);
}
}
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:
- this() only works in a constructor.
- 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.
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 . Next, 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:- Static fields of the Parent class .
- Static initialization block of the Parent class .
- Static fields of the Child class .
- The static initialization block of the Child class .
- Non-static fields of the Parent class .
- Not a static initialization block of the Parent class .
- The constructor of the Parent class .
- Non-static fields of Child class .
- Not a static initialization block of the Child class .
- Child class constructor .
37. What kind of relationships do you know between classes (objects)?
There are two kinds of relationships between classes in Java:- IS-A relationship
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
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. Composition 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.
GO TO FULL VERSION