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 5

Published in the Random EN group
Hello, hello! Today, Java developers are in high demand. Of course, I cannot provide you with a vacancy, but I will try to help you gain new knowledge and close some gaps. So we continue to analyze 250+ interview questions for Java developer. Links to previous parts of the analysis are at the end of the article.Analysis of questions and answers from interviews for 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 encapsulation elements. But I’ll remind you anyway. Access modifiers in Java are keywords that describe the level of access granted to a particular Java component. Access modifiers can be:
  • public — an element with this modifier will be publicly accessible. 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 the access modifier is not specified at all. It is similar to the previous one, except that visibility is allowed in descendant 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 Java developer.  Part 5 - 2

40. Name the main feature of static and variable methods

A very strange formulation - “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, for them you 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 the 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 bound to (belong to) an object, and in order to call them, you must have an instance (object) on which the method will be called. For example, a cat has a non-static method - meowing:
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 designated by the static keyword does not belong to an object of the class, but rather to the class, and it is loaded when the class itself is loaded. Static elements are the only ones for the entire program, and regular elements are the only ones for a specific object. Static can be:
  • class fields;
  • class initialization block;
  • class method;
  • internal 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?

I already mentioned this in the previous article: a method cannot be abstract and static at the same time. The abstractness of a method means that it must be overridden in the successor. 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 start cursing. If you have such a situation, you should seriously think about the correctness of the architecture of your application (after all, there is clearly something wrong with it).Analysis of questions and answers from interviews for 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 regular 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 specific objects of the class as you want, and each of them will have a reference to itself inside - this . And how then do you understand which particular this link you need to take? But no way. Therefore, static elements cannot refer to non-static ones, without a reference 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 the static method petTheCat calls the normal, non-static method of the Cat object - getName .

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

As we remember, there is no multiple inheritance in Java. Interfaces are something of an alternative to it. The interface looks 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 an interface implementation by a class:
class Cat implements Animal {

   @Override
   public void voice() {
       System.out.println("Meow! Meow! Meow!");
   }
}
The main thing you need to know about using interfaces is:
  1. Interface methods should contain only 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 written separated by commas: class Lion implements Animal, Wild .
  3. Interfaces are created using the keyword - interface .
  4. When implementing an interface by a class, the keyword is implements .
  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 many forms).
  7. As a rule, access modifiers for methods are not written in the interface: they are public by default , and other modifiers other than public cannot be specified. Since Java 9, you can use private modifiers for 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 whether interfaces can be final is of course not. After all, the very essence of interfaces is to be implemented. And as we all remember very well, final at the class level makes it non-inheritable, and in the case of an interface, non-implementable. Why do we need an interface that cannot be implemented and used? That's right - there's no need! And the compiler thinks so)) Analysis of questions and answers from interviews for Java developer.  Part 5 - 4The meaning only appeared with the introduction of static methods in interfaces with Java 8, but this did not change the fact that the interface cannot be final. I talked about interfaces, very superficially, because... this is a broad topic. Read more about this in the articles about interfaces in Java and the difference between abstract classes and interfaces .

46. ​​Where can I initialize static fields?

Static fields can be initialized:
  • directly upon declaration, through the equal sign = ;
  • in the static initialization block;
  • in a non-static initialization block, but you must understand that every 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 the interface. What if you don't want to implement an interface in a class, but you still need an object of the interface type? And most likely, this will be a single case of using this object. And you don't need to create a full-fledged implementation class. How will you do this? Right! Through an anonymous class! Analysis of questions and answers from interviews for Java developer.  Part 5 - 5Let's say we have some Animal interface :
public final interface Animal {
   public void voice();
}
If we want to instantiate this interface through 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 will not be able to create an interface/abstract class object, since there are unimplemented/abstract methods. As I mentioned, anonymous classes are used not only to implement abstract methods of an interface, but also to implement abstract methods of an abstract class. This approach is good for situations when an object is used one-time or a given implementation of methods is needed only once, and there is no need to create a separate class that will implement the required abstract class/interface. But I will also note that the use of anonymous classes is a rare occurrence in 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?

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

49. What is the “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 Map ? Then you need 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 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 a primitive wrapper. 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 analogue class if necessary (for example, int to Integer ). Unboxing is the reverse process of the previous one: automatically converting 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 were able to become full-fledged members of the OOP language - Java. Analysis of questions and answers from interviews for Java developer.  Part 5 - 7To learn more about this topic, I strongly 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. In Java, there are 4 types of such internal classes: 1. Inner class This type of class is declared directly in the body of another class. A nested inner class can access any private field or method of an instance 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 framing 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. It is because an inner class is implicitly associated with 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 a static access modifier near the class declaration. Since this kind of class does not have access to non-static fields of the outer class, it is more like the static part of the outer class than an inner class. In this case, the class data has access to all static members of the outer class, even private ones. 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 do not need an object of an outer class to create an object of a nested static class. 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, and the creation and use of an object of a local class is possible exclusively 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 even 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, since using these two modifiers will cause a 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 using Internal static and non-static classes are used because sometimes it is better to embed small classes within larger ones and keep them together: this way they will have higher cohesion and a common purpose. Actually, the use of nested classes increases code encapsulation. The reason for choosing local classes may be that a given class is used exclusively within a single method. In this case, is it necessary to spread the code throughout the application? 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 abstract class will be needed only once, so there is no need to create a separate, full-fledged class with an implementation for this. Instead, in a simple way, we implemented the method(s) we needed through an anonymous class, used this object and forgot about it (well, the Garbage collector remembered about it). This and thisAnalysis of questions and answers from interviews for Java developer.  Part 5 - 8 article will help you study internal classes in more detail .

51. What access modifiers can a class have?

As we remember, there are different types of classes and different access modifiers are applicable to them:
  • an outer class can have the access modifier public or be without a modifier (default modifier);
  • the inner class supports all 4 access modifiers;
  • nested static class supports all access modifiers except protected , because this modifier implies inheritance, which contradicts the static member of the class (static elements are not inherited);
  • a local class can only have a default modifier (i.e., no modifier at all);
  • anonymous class : if 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 Java developer.  Part 5 - 9
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION