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 5

Published in the Random EN group
Hello, hello! Java developers are in high demand today. Of course, I cannot provide you with a vacancy, but I will try to help you a little in gaining new knowledge and filling in some gaps. So we continue to analyze 250+ questions from interviews for a Java developer. Links to the previous parts of the analysis are at the end of the article.Analysis of questions and answers from interviews for a Java developer.  Part 5 - 1

39. What are access modifiers in Java? Name them. What are they used for?

I previously described access modifiers in the question about Java elements responsible for encapsulation. But I'll still remind you. Access modifiers in Java are keywords that describe the level of access granted to a particular Java component. Access modifiers can be:
  • public - the element with this modifier will be public. Those. fields and methods, classes declared with the public modifier are visible to other classes both from the current package and from external packages;
  • protected - an element with this modifier will be accessible from anywhere in the current class of the current package or in descendant classes, even if they are in other packages;
  • default , or missing modifier - this modifier is used implicitly when no access modifier is specified at all. It is similar to the previous one, except that it allows visibility in derived classes that are in other packages;
  • private is the most private of all modifiers, allowing access to the element only within the current class.
Analysis of questions and answers from interviews for a Java developer.  Part 5 - 2

40. Name the main feature of static and variable methods

A very strange wording is “variable methods”. Surely this refers to ordinary, non-static methods. So, the main difference is that static methods belong to the class and, in fact, they do not need to create an instance of this class: it can only be called using the class type. For example, we have a static method to pet a cat:
public class CatService {
   public static void petTheCat(Cat cat) {
       System.out.println("Погладить кота - " + cat.getName());
   }
We don't need an instance of the CatService class to call it :
Cat cat = new Cat(7, "Bobi");
CatService.petTheCat(cat);
While ordinary methods are attached (belonging) to an object, and in order to call them, it is necessary to have an instance (object) on which the method will be called. For example, a cat has a non-static method - meow:
class Cat {
   public void mew() {
       System.out.println("Meow! Meow! Meow!");
   }
To call this method, we need a specific instance of the cat:
Cat cat = new Cat(7, "Bobi");
cat.mew();

41. What are the main restrictions on static and "variable" methods?

As I said earlier, the main limitation of a regular method is that there must always be some instance on which this method will be called. But a static method does not require this, but it cannot refer to the this reference - to the elements of the current object - since the current object does not exist for it.

42. What does the static keyword mean? Can a static method be overridden or overloaded?

An element marked with the static keyword does not belong to the class object, but to the class, and it is loaded when the class itself is loaded. Static elements are the only ones for the whole program, and ordinary ones are the only ones for a specific object. Static can be:
  • class fields;
  • class initialization block;
  • class method;
  • inner classes of a class (however, that is still a tautology).
A static method cannot be overridden: it belongs to the class and is not inherited, but at the same time it can be overloaded.

43. Can a method be static and abstract at the same time?

In the previous article, I already mentioned this: a method cannot be abstract and static at the same time. The abstractness of a method means that it must be overridden in a descendant. At the same time, a static method belongs to the class and cannot be overridden: this will cause a contradiction, which the compiler will see and begin to swear. If you have such a situation, you should seriously think about the correct architecture of your application (because something is clearly wrong with it).Analysis of questions and answers from interviews for a Java developer.  Part 5 - 3

44. Is it possible to use static methods in the middle of regular ones? Vice versa? Why?

Static methods can be used in ordinary ones, since nothing prevents this. At the same time, the reverse situation is impossible: a static method cannot use a regular method without having a reference to a specific instance of this class. And as we remember, the this reference is not available for static class members : there can be as many concrete objects of the class as you like, and each of them will have a reference to itself inside - this . And how then to understand which link this needs to be taken? But no way. Therefore, static elements cannot refer to non-static ones without referring to a specific object. Actually, a static method can use a non-static method only if it has a reference to a specific object. For example, the one that came as an argument:
public static void petTheCat(Cat cat) {
   System.out.println("Погладить кота - " + cat.getName());
}
Here we see that in the static method petTheCat, the usual, non-static method of the Cat object , getName , is called .

45. What is an interface? Can there be a final interface?

As we remember, there is no multiple inheritance in Java. Interfaces are something like its alternative. An interface is like a very stripped-down class. They define functionality without a specific implementation, which is implemented by classes that implement (implement) these interfaces. Interface example:
public interface Animal {
    void voice();
}
An example of implementing an interface by a class:
class Cat implements Animal {

   @Override
   public void voice() {
       System.out.println("Meow! Meow! Meow!");
   }
}
The main things to know about using interfaces are:
  1. Interface methods should only contain a header, without a specific method body, i.e. must be abstract (but without using the abstract keyword ). The exception to this is static and default methods, which require a method body.
  2. A class can implement many interfaces (as I said, this is an alternative to multiple inheritance), which are separated by commas: class Lion implements Animal, Wild .
  3. Interfaces are created using the keyword - interface .
  4. When a class implements an interface, the implements keyword is used .
  5. A class that implements a particular interface must implement all of its abstract methods, or must declare itself abstract.
  6. The main purpose of using interfaces is to implement polymorphism (the ability of objects to take on many forms).
  7. In an interface, as a rule, you do not write access modifiers for methods: they are public by default , and other modifiers other than public cannot be set. Since Java 9 you can use private modifiers on methods.
  8. Interface variables are static final by default , in other words, constants: they always need to be initialized directly in the interface.
  9. You cannot create an interface object.
The answer to the question of whether interfaces can be final is, of course, no. After all, the very essence of interfaces is that they are implemented. And as we all remember very well, final at the class level makes it not inherited, and in the case of an interface, it is not implemented. Why do we need an interface that cannot be implemented and used? That's right - no need! And the compiler thinks so)) Analysis of questions and answers from interviews for a Java developer.  Part 5 - 4It only made sense with the introduction of static methods in interfaces with Java 8, but this did not change the fact that an interface cannot be final. I talked about interfaces, very superficially, because. this is a broad topic. For more on this, see the articles on interfaces in Java and the difference between abstract classes and interfaces .

46. ​​Where can you initialize static fields?

Static fields can be initialized:
  • directly at the declaration, through the equal sign = ;
  • in a static initialization block;
  • in a non-static initialization block, but at the same time you must understand that each time an object is created, this field will be overwritten by this initialization block;
  • in the class constructor. Each time this constructor is called (that is, when an object is created through this constructor), this field will be overwritten;
  • in static methods;
  • in non-static methods;
  • in internal static and non-static, local and anonymous classes.

47. What are anonymous classes?

Anonymous classes are classes that do not have their own type. What am I talking about? When we talked about interfaces, I mentioned that you can't create an interface object: you can only create an object of a class that implements an interface. But what if you don't want to implement an interface in some class, but you still want an object of the interface type? And most likely, it will be a single case of using this object. And you do not need to create a full-fledged implementation class. How will you do it? Right! Through an anonymous class! Analysis of questions and answers from interviews for a Java developer.  Part 5 - 5Suppose we have some Animal interface :
public final interface Animal {
   public void voice();
}
If we want to instantiate a given interface via an anonymous class:
Animal cat = new Animal() {
   @Override
   public void voice() {
       System.out.println("Meow! Meow! Meow!");
   }
};
And then you can safely use this object and its implemented method - voice. That is, an anonymous class implements this interface and all its abstract methods right here and now. Otherwise, we cannot create an interface / abstract class object, since there are not implemented / abstract methods. As I mentioned, anonymous classes are used not only to implement the abstract methods of an interface, but also to implement the abstract methods of an abstract class. This approach is good for situations where an object is used once or a given implementation of methods is needed only once, and there is no need to create a separate class that will implement the necessary abstract class/interface. But I also note that the use of anonymous classes is a rare occurrence in the work: as a rule, preference is still given to ordinary classes. You can read more about anonymous classes in this article..

48. What are primitive classes?

To me, this is a very strange question, and perhaps this is such a trap question, because in Java there is no such thing as primitive classes, except that there is a concept of primitive types, which we already considered earlier. As we remember, Java has 8 primitive types - byte , short , int , long , float , double , char , boolean .Analysis of questions and answers from interviews for a Java developer.  Part 5 - 6

49. What is a wrapper class?

The main problem with using primitive types in Java is that they are still not classes, and Java is still an OOP language. That is, programs written in this language are reduced to interaction between objects. Well, primitives are not objects. They don't have methods, not even the standard ones from the Object class . Well, what if we needed to use a primitive as a key in a Map ? Then it needs to call the hashCode method . You can also call the equals method there. What then? There can be very, very many moments where there should be exactly a class, and not a primitive, which makes primitives unused and undesirable elements in the program, because this destroys the very idea of ​​​​OOP. But not everything is as bad as it seems. After all, Java has the concept of wrapping primitives. Each primitive type has an analogue class:
  • byte -> Byte class
  • short -> short class
  • int -> Integer class
  • long -> Long class
  • float -> float.class
  • double -> Double class
  • char -> character.class
  • boolean -> boolean class
This is a representation of simple types, but in the form of full-fledged classes with a bunch of diverse and functional methods. For convenient use of these classes, the concepts of autoboxing and unboxing were introduced. Autoboxing - automatic conversion of a primitive type to an analog class if necessary (for example, int to Integer ). Unboxing is the reverse process of the previous one: automatic conversion of a primitive wrapper class to a primitive type (for example, Integer to int ). Thanks to the introduction of primitive wrapper classes and the autoboxing and unboxing processes , primitive types could become full-fledged members of the Java OOP language.Analysis of questions and answers from interviews for a Java developer.  Part 5 - 7To learn more about this topic, I highly recommend reading this article .

50. What is Nested class? When is it used?

Nested class is an inner class that is a member of another class. There are 4 kinds of such inner classes in Java: 1. Inner class This kind of class is declared directly in the body of another class. A nested inner class can access any private field or instance method of the outer class. As an example, let's create a zoo in which we will have an animal - a zebra:
public class Zoo {
   class Zebra {
       public void toFeed(String food) {
           System.out.println("Дать зебре - " + food);
       }
   }
}
Nothing complicated, right? Let's take a look at an example of creating an inner class object:
Zoo.Zebra zebra = new Zoo().new Zebra();
zebra.toFeed("яблоко");
As you have already seen, it is imperative to create an object of the enclosing class, based on the reference of which you can create an object of the inner class. I would also like to note that a nested inner class cannot have static methods or static fields in it. It is because the inner class is implicitly related to the object of its outer class, and it cannot declare any static methods within itself. 2. Static nested classes This class is similar to the previous one, only it has the static access modifiernext to the class declaration. Since this kind of class does not have access to the non-static fields of the outer class, it is more like the static part of the outer class than the inner class. At the same time, class data has access to all static members of the outer class, even private ones. An example of a static nested class:
public class Zoo {
   static class Zebra {
       public void toFeed(String food) {
           System.out.println("Дать зебре - " + food);
       }
   }
}
The creation method is slightly different from the previous one:
Zoo.Zebra zebra = new Zoo.Zebra();
zebra.toFeed("яблоко");
Here we don't need an outer class object to create a nested static class object. From the outer class, we only need its type so that we can find the location of the nested class. 3. Local classes Local classes are classes declared inside the body of a method, while the creation and use of an object of a local class is possible only within this method. Example:
public class Zoo {
   public void toFeed(String animal, String food) {
       switch(animal){
           case "зебра":
               class Zebra {
                   void toFeedZebra(String food) {
                       System.out.println("Дать зебре - " + food);
                   }
               }
               Zebra zebra = new Zebra();
               zebra.toFeedZebra(food);
               ...
Usage example:
Zoo zoo = new Zoo();
zoo.toFeed("зебра", "яблоко");
Without seeing the code for the toFeed method , you wouldn't suspect the existence of a local class, would you? A local class cannot be static or transient , but it can be marked as abstract or final (only OR, because the use of these two modifiers will conflict). 4. Anonymous classes We have already talked about anonymous classes above, and as you remember, they can be created from two sources - interfaces and classes. Reasons for use Inner static and non-static classes are used because sometimes it's better to nest small classes inside larger ones and keep them together so they have more cohesion and a common purpose. Actually, the use of nested classes increases the encapsulation of the code. The reason for choosing local classes may be that a given class is used exclusively within a single method. Do I need to spread the code around the application in this case? No. But at the same time, I will add that in my practice I have never seen the use of local classes, because the need for them is highly controversial. Well, the reason for using anonymous classes may be that a specific implementation of an interface or an abstract class will be needed only once, so there is no need to create a separate, full-fledged class with an implementation for it.Analysis of questions and answers from interviews for a Java developer.  Part 5 - 8To learn more about inner classes, this and this article will help you.

51. What access modifiers can a class have?

As we remember, there are different types of classes and different access modifiers are applicable for them:
  • the outer class can have a public access modifier or be without a modifier (the default modifier);
  • the inner class supports all 4 access modifiers;
  • a nested static class supports all access modifiers except protected , because this modifier implies inheritance, which contradicts the static member of the class (static members are not inherited);
  • a local class can only be with a default modifier (that is, without a modifier at all);
  • anonymous class : there is no class type declaration, then there are no access modifiers at all.
This is where we will stop today. See you soon!Analysis of questions and answers from interviews for a Java developer.  Part 5 - 9Analysis of questions and answers from interviews for a Java developer.  Part 5 - 10
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION