Java OOPS Interview Questions And Answers

Interview Questions

62 Java OOPS Interview Questions And Answers – OOPS Java Interview Questions For Experienced 2018 from Codingcompiler. Test your Java OOPS knowledge by answering these tricky interview questions on Java OOPS. Let’s start learning OOPS Java interview questions and prepare for Java interviews. All the best for your future and happy learning.

62 Java OOPS Interview Questions

  1. Name the principles of OOP and tell about each.
  2. Give the definition of “class”.
  3. What is a class field / attribute?
  4. How to organize access to the fields of the class?
  5. Give the definition of “constructor”.
  6. What is the difference between default constructors, copying and constructor with parameters?
  7. What modifications of the access level do you know, tell us about each of them.
  8. Tell us about the features of the class with a single closed constructor.
  9. What do the keywords “this”, “super” say, where and how can they be used?
  10. Give the definition of “method”.
  11. What is a method signature?
  12. What methods are called overloaded?
  13. Can non-static methods overload static?
  14. Tell about redefinition of methods.
  15. Can a method take a different number of parameters (variable length arguments)?
  16. Is it possible to narrow the access level / return type when redefining the method?
  17. How to get access to the overridden methods of the parent class?
  18. What transformations are called descending and ascending?
  19. How is overriding different from overloading?
  20. Where can I initialize static / non-static fields?
  21. Why is the instanceof operator needed?
  22. Why do we need and what are the initialization blocks?
  23. What is the order of calling constructors and initialization blocks of two classes: a descendant and its ancestor?
  24. Where and what is the abstract modifier used for?
  25. Is it possible to declare a method abstract and static at the same time?
  26. What does the static keyword mean?
  27. To which Java constructs is the static modifier applicable?
  28. What happens if an exception occurs in the static code block?
  29. Is it possible to overload the static method?
  30. What is a static class, what are the features of its use?
  31. What are the features of initialization of final static variables?
  32. How does the static modifier affect a class / method / field?
  33. What does the final keyword mean?
  34. Give the definition of “interface”.
  35. What modifiers have fields and methods of interfaces by default?
  36. Why can’t I declare an interface method with a final or static modifier?
  37. What types of classes are in java (nested … etc.)
  38. What are the features of creating nested classes: simple and static.
  39. What do you know about nested classes, why are they used? Classification, use cases, violation of encapsulation.
  40. What is the difference between nested and inner classes?
  41. Which classes are called anonymous?
  42. How from the nested class to get access to the field of the outer class?
  43. How can I access the local variable of a method from an anonymous class declared in the body of this method? Are there any restrictions for such a variable?
  44. How is any custom class related to the Object class?
  45. Tell us about each of the methods of the Object class.
  46. ​​What is the equals () method. How it differs from the operation ==.
  47. If you want to override equals (), which conditions must be satisfied for the overridden method?
  48. If equals () is overridden, are there any other methods that should be overridden?
  49. What are the features of the hashCode and equals methods? How are the hashCode and equals methods implemented in the Object class? What rules and conventions exist to implement these methods? When do they apply?
  50. Which method returns a string representation of an object?
  51. What happens if you redefine equals without overriding hashCode? What problems may arise?
  52. Are there any recommendations on which fields should be used when calculating hashCode?
  53. What do you think, will there be any problems if an object that is used as a key in a hashMap has a field that participates in the definition of hashCode?
  54. What is the difference between an abstract class and an interface, in which cases what will you use?
  55. Is it possible to access private class variables and, if so, how?
  56. What is volatile and transient? For what and in what cases it would be possible to use default?
  57. Expanding modifiers for inheritance, overriding and hiding methods. If the parent class has a method declared as private, can the heir expand its visibility? And if protected? And narrow visibility?
  58. Does it make sense to declare the method private final?
  59. What are the features of the initialization of final variables?
  60. What happens if a single class constructor is declared final?
  61. What is finalize? Why is it needed? What can you tell about the garbage collector and the algorithms of its work.
  62. Why is the clone method declared protected? What is needed to implement cloning?

Related Java Tutorials For Beginners

Introduction to Java Programming

Java Keywords Tutorial For Beginners

Java Data Types Tutorial For Beginners

Java Operators Tutorial For Beginners

Java Control Flow Statements Tutorial

Java Performance Tuning Tips

Java Class Tutorial For Beginners

Java Exceptions Tutorial For Beginners

Java Annotations Tutorial For Beginners

Java Generics Tutorial For Beginners

Java Enumeration Tutorial For Beginners

Java Class Instance Tutorial For Beginners

OOPS Java Interview Questions And Answers

1. Name the principles of OOP and tell about each.

Objective-oriented programming (OOP) is a programming methodology based on the representation of a program as a set of objects, each of which is an instance of a particular class, and the classes form an inheritance hierarchy.

The basic principles of OOP: abstraction, encapsulation, inheritance, polymorphism.

Abstraction – means the allocation of significant information and exclusion from consideration of insignificant. In terms of programming, this is the proper division of the program into objects. Abstraction allows you to select the main characteristics and omit the secondary.

Example: description of positions in the company. Here the title of the post is relevant information, and the description of the duties of each post is background information. For example, the main characteristic for a “director” is that this position controls something, but what exactly (HR director, financial director, executive director) is already secondary information.

Encapsulation is a property of the system that allows you to combine data and methods that work with them in a class. For Java, it will be correct to say that encapsulation is “implementation hiding”. The life example is a TV remote control. We press the “increase the volume” button and it increases, but at this moment there are dozens of processes that are hidden from us.

For Java: you can create a class with 10 methods, for example, calculating the area of ​​a complex figure, but make them 9 private. The 10th method will be called “calculate Area ()” and declared public, and the necessary methods hidden from the user will already be called in it. This is what the user will call.

Inheritance is a property of the system that allows you to describe a new class on the basis of an existing one with partially or fully borrowed functionality. The class from which inheritance is made is called the base, parent, or superclass. A new class is a descendant, heir, child, or derived class.

Polymorphism  is a property of the system to use objects with the same interface without information about the type and internal structure of the object. An example (slightly remade) from Thinking in Java:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

public interface Shape {

   void draw();

   void erase();

}

public class Circle implements Shape {

   public void draw() {

       System.out.println(“Circle.draw()”);

   }

}

public class Triangle implements Shape {

   public void draw() {

       System.out.println(“Triangle.draw()”);

   }

}

public class TestPol {

   public static void main(String[] args) {

       Shape shape1 = new Circle();

       Shape shape2 = new Triangle();

       testPoly(shape1);

       testPoly(shape2);

   }

   public static void testPoly(Shape shape) {

       shape.draw();

   }

}

//Output to console:

//Circle.draw()

//Triangle.draw()

There is a common “Figure” interface and its two implementations “Triangle” and “Circle”. Everyone has a “draw” method. Thanks to polymorphism, we don’t need to write a separate method for each of the many shapes to call the “draw” method. Calling a polymorphic method allows one type to express its difference from another, of a similar type, although they come from the same basic type. This difference is expressed by the various actions of methods called through the base class (or interface).

Here is an example of polymorphism (also called dynamic linking, or late linking, or linking at runtime), which demonstrates how the program that belongs to the transmitted object will be executed at runtime.

If there were no polymorphism and late binding, then the same program would look like this:

1

2

3

4

5

6

public static void testPolyCircle(Circle circle) {

       circle.draw();

   }

   public static void testPolyTriangle(Triangle triangle) {

       triangle.draw();

   }

Those. for each class (figure) we would write a separate method. There are two of them, and if there are hundreds of figures (classes)?

2. Give the definition of “class”.

A class is a handle to the general properties of a group of objects. These properties can be as characteristics of objects (size, weight, color, etc.), and behavior, roles, etc.

3. What is a class field / attribute?

The field (attribute) of a class is a characteristic of an object. For example, for a figure, this may be the name, area, perimeter.

1

2

3

4

5

6

7

public class Circle implements Shape {

   private String name;

   private Double area;

   private String perimeter;

}

4. How to organize access to the fields of the class?

The access modifier is private. Access via get \ set methods.

5. Give the definition of “constructor”.

A constructor is a special method that is called when a new object is created. The constructor initializes the object directly during creation. The name of the constructor is the same as the name of the class, including the case, and the syntax of the constructor is similar to a method without a return value.

1

2

3

4

5

public class Circle implements Shape {

  public Circle() {

   }

}

6. What is the difference between default constructors, copying and constructor with parameters?

The default constructor does not accept any parameters. The copy constructor takes a class object as a parameter. The constructor with parameters accepts parameters as input (usually necessary for initialization of class fields).

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

   //default constructor

   public Circle() {

   }

   //copy constructor

   public Circle(Circle circle) {

       this(circle.getName(), circle.getArea(), circle.getPerimeter()); //the constructor will be called with the parameters below.

   }

   

   //constructor with parameters

   public Circle(String name, Double area, String perimeter) {

       this.name = name;

       this.area = area;

       this.perimeter = perimeter;

   }

I draw your attention to the fact that the topic of copying (clone ()) is quite deep with the possibility of many implicit problems. 

7. What modifications of the access level do you know, tell us about each of them.

  • private (private) – access to a member of the class is not provided to anyone except the methods of this class. Other classes in the same package also cannot access private members.
  • default, package, friendly, access by default when no modifier is present – a member of the class is considered open inside its own package, but not available for code located outside this package. if package2.Class2 extends package1.MainClass , then in Class2, methods without an identifier from MainClass will not be visible .
  • protected — access within a package and inheritance classes. Access in a class from another package will be to the public and protected methods of the main class. Those. if package2.Class2 extends package1.MainClass , then inside package2.Class2 the methods with the identifier protected from MainClass will be visible.
  • public (open) – access for everyone from any other project code

Modifiers in the list are arranged by increasing visibility in the program.

8. Tell us about the features of the class with a single closed constructor.

It is impossible to create a class object with a single private constructor outside the class. Therefore, one cannot inherit from such a class. When you try to inherit, you will get an error:  There is no default constructor available in the name of the Class . And when trying to create an object of this class: Name Class () has private access in Class Name

9. What do the keywords “this”, “super” say, where and how can they be used?

super – is used to refer to the base class, and this to the current one. Example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

public class Animal {

   public void eat() {

       System.out.println(“animal eat”);

   }

}

public class Dog extends Animal {

   public void eat() {

       System.out.println(“Dog eat”);

   }

   public void thisEat() {

       System.out.println(“Call Dog.eat()”);

       this.eat();

   }

   public void superEat() {

       System.out.println(“Call Animal.eat()”);

       super.eat();

   }

}

public class Test {

   public static void main(String[] args) {

       Dog dog = new Dog();

       dog.eat();

       dog.thisEat();

       dog.superEat();

   }

}

Dog eat

Call Dog.eat()

Dog eat

Call Animal.eat()

animal eat

If you write super (), then the constructor of the base class will be called, and if this (), then the constructor of the current class. This can be used, for example, when calling a constructor with parameters:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

public Dog() {

       System.out.println(“Call empty constructor”);

   }

   public Dog(String name) {

       System.out.println(“Call constructor with Name”);

       this.name = name;

   }

   public Dog(String name, Double weight) {

       this(name);

       this.weight = weight;

       System.out.println(“Call constructor with Name and Weight”);

   }

}

..

public static void main(String[] args) {

Dog dog1 = new Dog(“name”, 25.0);

}

//Conclusion

Call constructor with Name

Call constructor with Name and Weight

Related Java Interview Questions

  1. Core Java Interview Questions
  2. JSF Interview Questions
  3. JSP Interview Questions
  4. JPA Interview Questions
  5. Spring Framework Interview Questions
  6. Spring Boot Interview Questions
  7. Core Java Multiple Choice Questions
  8. 60 Java MCQ Questions And Answers
  9. Aricent Java Interview Questions
  10. Accenture Java Interview Questions
  11. Advanced Java Interview Questions For 5 8 10 Years Experienced
  12. Core Java Interview Questions For Experienced

Java Object Oriented Programming Interview Questions

10. Give the definition of “method”.

A method is a sequence of commands that are invoked by a specific name. We can say that this is a function and a procedure (in the case of the void method).

11. What is a method signature?

The method signature in Java is the name of the method plus the parameters (and the order of the parameters matters).

The method signature does not include the return value, the exceptions thrown by it, or modifiers.

Keywords public, protected, private, abstract, static, final, synchronized, native, strictfp incl. annotations for the method are modifiers and are not part of the signature.

12. What methods are called overloaded?

Java allows you to create multiple methods with the same name, but different signatures. Creating a method with the same name but with a different set of parameters is called overloading. Which of the overloaded methods should be executed when invoked, Java determines based on the actual parameters.

1

2

3

4

5

public void method() { }

public void method(int a) { }

public void method(String str) { }

13. Can non-static methods overload static?

Yes. These will be just two different methods for the program. Static will be available by class name.

Java OOPS Interview Questions And Answers For Experienced

14. Tell about redefinition of methods. Can static methods be redefined?

A method in a descendant class that matches its signature with a method from its parent class is called an overridden method. The basic static method cannot be overridden : Instance method method name in class Heir cannot override method method name in parent Class

15. Can a method take a different number of parameters (variable length arguments)?

Yes. The entry has the form method (type … val) . For example, public void method (String … strings) , where strings is an array, i.e. can write

1

2

3

4

5

public void method (String … strings) {

       for (String s : strings) {

           

       }

   }

16. Is it possible to narrow the access level / return type when redefining the method?

When overriding a method, you cannot narrow the method access modifier (for example, from public in MainClass to private in Class extends MainClass). It is impossible to change the type of the return value when redefining the method, there will be an error attempting to use incompatible return type. But you can narrow the return value if they are compatible. For example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

public class Animal {

   public Animal eat() {

       System.out.println(“animal eat”);

       return null;

   }

   

   public Long calc() {

       return null;

   }

}

public class Dog extends Animal {

   public Dog eat() {

       return new Dog();

   }

/*attempting to use incompatible return type

   public Integer calc() {

       return null;

   }

*/

}

17. How to get access to the overridden methods of the parent class?

super.method ();

18. What transformations are called descending and ascending?

Transformation from descendant to ancestor is called ascending, from ancestor to descendant – descending. A downward transformation must be explicitly indicated by specifying a new type in brackets.

For example:

1

2

3

4

Animal dog = new Dog(); //upstream transformation. Access to all methods that only the Dog class has will be lost.

int x = 100;

byte y = (byte) x;  //downward conversion. Must be explicit

19. How is overriding different from overloading?

Redefinition is used when you rewrite (rewrite, override) ALREADY an existing method. Overloading is the use of the same name, but with different input parameters. For example, we need the toString () method for our class to produce some meaningful text. Then we override the method from the Object class and implement this method as we need it.

1

2

3

4

@Override

public String toString() {

return “I want the text to be written, not the class name @ 2234SD!”

}

Whereas overloading is usually used in order not to invent a new name every time, when the methods differ only in the input parameters. During overloading, the required method is determined at the compilation stage on the basis of the signature of the method being called, whereas during redefinition, the required method will be identified at run time based on the actual type of the object.

20. Where can I initialize static / non-static fields?

Static fields can be initialized upon declaration, in a static or dynamic initialization block. Non-static fields can be initialized when declaring, in a dynamic initialization block, or in a constructor.

Java OOPS Interview Questions With Examples

21. Why is the instanceof operator needed?

The instanceof operator returns true if the object is an instance of a class or its descendant.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

public class MainClass {

   public static void main(String[] a) {

   String s = “Hello”;

   int i = 0;

   String g;

   if (s instanceof java.lang.String) {

   // get here because the expression will be true

   System.out.println(“s is a String”);

   }

   if (i instanceof Integer) {

   // This will be displayed, because autopacking will be used (int -> Integer)

   System.out.println(“i is an Integer”);

   }

   if (g instanceof java.lang.String) {

   // g is not initialized and therefore we will not get here, because

   // g – null and instanceof will return false for null.

   System.out.println(“g is a String”);

   }

}

22. Why do we need and what are the initialization blocks?

Initialization blocks are sets of field initialization expressions enclosed in braces and placed inside a class outside the declarations of methods or constructors.

The initialization block is executed in the same way as if it were located in the upper part of the body of any constructor. If there are several initialization blocks, they are executed in the order in the class text. The initialization block is able to generate exceptions if their declarations are listed in the throws clauses of all the class constructors.

There are static and non-static initialization blocks. It is also possible to create such a block in an anonymous class.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

class Foo {

static List<Character> abc;

static {

abc = new LinkedList<Character>();

for (char c = ‘A’; c <= ‘Z’; ++c) {

abc.add( c );

}

}

}

//An example of a non-static initialization block

class Bar {

{

System.out.println(“Bar: new instance”);

}

}

//An example of initialization in an anonymous class.

JFrame frame = new JFrame() {{

add(new JPanel() {{

add(new JLabel(“Habrahabr?”) {{

setBackground(Color.BLACK);

setForeground(Color.WHITE);

}});

}});

}};

23. What is the order of calling constructors and initialization blocks of two classes: a descendant and its ancestor?

First, all static blocks from the first ancestor to the last heir are called. Then the dynamic initialization block and the constructor are called in pairs in the same sequence (from ancestor to the last descendant).

A good picture that demonstrates what is actually happening when initializing from the javarush.ru resource:

Here is a simple example that demonstrates this:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

public class Pet {

   private String name;

   static {

       System.out.println(“Static block in Pet”);

   }

   {

       System.out.println(“First block in Pet”);

   }

   {

       System.out.println(“Second block in Pet”);

   }

   public Pet() {

       System.out.println(“Pet empty constructor”);

   }

   public Pet(String name) {

       System.out.println(“Pet constructor with Name ” + name);

       this.name = name;

   }

}

public class Cat extends Pet {

   private String name;

   static {

       System.out.println(“Static block in Cat”);

   }

   {

       System.out.println(“First block in Cat”);

   }

   {

       System.out.println(“Second block in Cat”);

   }

   public Cat() {

       System.out.println(“Cat empty constructor”);

   }

   public Cat(String name) {

       super(name); // without this will call super(). If this line is removed, the constructor Pet () will be called;

       System.out.println(“Cat constructor with Name: ” + name);

       this.name = name;

   }

}

public class TestInitOrder {

   public static void main(String[] args) {

       Cat cat = new Cat(“Rizhick”);

   }

}

//Conclusion

Static block in Pet

Static block in Cat

First block in Pet

Second block in Pet

Pet constructor with Name Rizhick

First block in Cat

Second block in Cat

Cat constructor with Name: Rizhick

24. Where and what is the abstract modifier used for?

An abstract class is a class on the basis of which objects cannot be created. At the same time, the heirs of the class may not be abstract, on the basis of which objects can be created, respectively, it is possible. In order to make a class abstract, you must specify the abstract modifier in front of its name.

Abstract method – a method that has no implementation. If a class has at least one abstract method, then the entire class must be declared abstract.

1

2

3

4

5

6

7

8

9

10

public abstract class Fighter {

   abstract void fight();

}

public class JudoFighter extends Fighter {

   @Override

   void fight() {

       System.out.println(“I teach Judo, hands waving!”);

   }

}

Using abstract classes and methods allows you to describe some kind of abstraction, which must be implemented in other classes. For example, we can create an abstract class Fighter and declare an abstract method fight () in it . Since There can be a lot of wrestling styles, for example, for JudoFighter extends Fighter,  the fight () method will describe judo techniques, etc.

25. Is it possible to declare a method abstract and static at the same time?

Not. Get: Illegal combination of modifiers: ‘abstract’ and ‘static’ . The abstract modifier says that the method will be implemented in another class, and static on the contrary indicates that this method will be accessible by the class name.

26. What does the static key field mean?

The static modifier says that a method or field of a class belongs not to an object, but to a class. Those. access can be obtained without creating a class object. Fields marked static are initialized when the class is initialized. For example, Class.forName (“MyClass”, true, currentClassLoader), where the second parameter indicates the need for initialization.

Methods declared as static are subject to a number of restrictions.

  • They can only call other static methods.
  • They should access only static variables.
  • They cannot refer to members of this or super.

27. To which Java constructs is the static modifier applicable?

  • To the method.
  • To the inner class.
  • To the field.
  • To imported classes (from 5th java). For example,  import static org.junit.Assert.assertThat;

28. What happens if an exception occurs in the static code block?

If you explicitly write any exception in a static block , the compiler does not compile the sources. This is all about the fact that the compiler is smart. Otherwise, the interaction with exceptions is the same as in any other place. If an unchecked exception is thrown in a static block , the class will not be initialized.

What exception is thrown when an error occurs in the initialization block?

For static :

  • java.lang.ExceptionInInitializerError – if the exception is inherited from RuntimeException .

For init :

  • exception , which caused the exception if it is inherited from RuntimeException .

True to static and init :

  • java.lang.Error – if the exception is caused by Error .
  • java.lang.ThreadDeath – death stream. Nothing falls out.

29. Is it possible to overload the static method?

You can overload, but you cannot override it.

1

2

3

4

5

6

7

8

   public Animal eat() {

       System.out.println(“animal eat”);

       return null;

   }

   public static Animal eat(String s) {

       System.out.println(“test static overload”);

       return null;

   }

OOPS Java Interview Questions And Answers

30. What is a static class, what are the features of its use?

This is a nested class that can access only the static fields of the class that wraps it, including private ones. Access to non-static fields of the framing class can only be done through a link to an instance of the framing object. The top-level class static  modifier is not applicable .

The example shows that there is no need to initialize the parent to initialize the internal static class. But in the case of the usual inner class this number will not work:

1

2

3

4

5

6

7

8

9

10

public class Test {

 class A { }

 static class B { }

 public static void main(String[] args) {

   /*will fail – compilation error, you need an instance of Test to instantiate A*/

   A a = new A();

   /*will compile successfully, no instance of Test is needed to instantiate B */

   B b = new B();

 }

}

Static nested classes do not have access to non-static fields and methods of the framing class, which is somewhat similar to static methods declared inside a class. Access to non-static fields and methods can be carried out only through a reference to an instance of the framing class. In this regard, static nested classes are very similar to any other top-level classes.

31. What are the features of initialization of final static variables?

Variables must be initialized during declaration or in a static block.

32. How does the static modifier affect a class / method / field?

The static modifier says that a method or field of a class belongs not to an object, but to a class.

Inside a static method you cannot call a non-static method by class name.

For the static class, see the answer above.

33. What does the final keyword mean?

Can be applied to fields, methods or classes. Depending on which entity this keyword is attached to, there will be a different meaning in its application.

  • For class. A class marked with final cannot have heirs.
  • For the method. The method marked with final cannot be redefined in classes of successors.
  • For the field. A field marked with the word final cannot change its value after initialization (initialized either in the description, or in the constructor, static or dynamic block).
  • The value of local variables, as well as method parameters marked with the word final, cannot be changed after assignment.

34. Give the definition of “interface”.

The interface keyword is used to create completely abstract classes. The interface creator defines the names of the methods, argument lists, and the types of return values, but not the body of the methods.

The presence of the word interface means that this is what all classes that implement this interface should look like. Thus, any code that uses a specific interface knows only which methods are called for that interface, but no more.

1

2

3

4

public interface SomeName{

   void method();

   int getSum();

}

35. What modifiers have fields and methods of interfaces by default?

An interface may contain fields, but they are automatically static (static) and immutable (final). All methods and variables are implicitly declared public.

36. Why can’t I declare an interface method with a final or static modifier?

In general, from the 8th version you can static, but you need to have the body of the method. for example

1

2

3

4

5

public interface Shape {

   static void draw() {

       System.out.println(“Wow! It is impossible!”);

   };

}

The final modifier is just meaningless. All default methods are abstract, i.e. they cannot be created without having implemented somewhere else, but it cannot be done if the method has an identifier  final .

37. What types of classes are in java (nested … etc)

38. What are the features of creating nested classes: simple and static.

  • Normal Classes ( Top level classes)
  • Interfaces ( Interfaces)
  • Enumerations ( Enum)
  • Static nested classes ( Static nested classes)
    • It is possible to refer to the internal static fields and methods of the wrapper class.
    • Internal static interfaces can contain only static methods.
  • Internal member classes ( Member inner classes)
    • It is possible to refer to the internal fields and methods of the wrapper class.
    • Cannot have static ads.
    • You cannot declare an interface this way. And if you declare it without an identifier static, it will automatically be added.
    • You cannot declare enums within this class.
    • If you need to explicitly get the this outer class –OuterClass.this
  • Local class ( Local inner classes)
    • Only visible within the block in which they are declared.
    • Cannot be declared as private/ public/ protected or static(for this reason, interfaces cannot be declared locally).
    • Cannot have inside static declarations (fields, methods, classes).
    • Have access to the fields and methods of the framing class.
    • You can access local variables and method parameters if they are declared with a modifier final.
  • Anonymous Classes ( Anonymous inner classes)
    • Local class with no name.

Tricky Java OOPS Interview Questions

39. What do you know about nested classes, why are they used? Classification, use cases, violation of encapsulation.

40. What is the difference between nested and inner classes?

41. Which classes are called anonymous?

A nested class is a class that is declared within the declaration of another class. Nested classes are divided into static and non-static (non-static). Actually non-static nested classes have another name – inner classes (inner classes).

Internal classes in Java are divided into three types:

  • inner member classes (member inner classes);
  • local classes (local classes);
  • anonymous classes (anonymous classes).

Internal member classes are not associated with the external class itself, but with its instance. At the same time, they have access to all of its fields and methods.

Local classes are defined in a block of Java code. In practice, most often the declaration occurs in the method of some other class. Although you can declare a local class inside static and non-static initialization blocks.

Anonymous class (anonymous class) is a local class with no name.

Using nested classes always leads to some violation of encapsulation – a nested class can refer to private members of the outer class (but not vice versa!). If this circumstance is taken into account in the architecture of your application, you should not pay special attention to it, since the inner class is only a specialized member of the outer class.

42. How from the nested class to get access to the field of the outer class?

If the nested class is not static and the field is not static, then you can simply refer to this field from the inner class, if only the inner class does not have a field with the same literal, in this case you need to refer to the outer class as follows: OuterClass.this. Field Name

* From the comment to the article: it is enough that the class is not static, and the field is static or not – does not matter for the Member Inner Class.

 

43. How can I access the local variable of a method from an anonymous class declared in the body of this method? Are there any restrictions for such a variable?

As well as local classes, anonymous can capture variables, access to local variables occurs according to the same rules:

  • An anonymous class has access to the fields of the outer class.
  • An anonymous class does not have access to local variables of the area in which it is defined, if they are not final (final) or unchangeable (effectively final).
  • Like other inner classes, declaring a variable with a name that is already taken overshadows the previous declaration.
  • You cannot define static members of an anonymous class.

Anonymous classes can also contain local classes. A constructor in an anonymous class cannot be.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

public class Animal {

   

   Integer classAreaVar2 = 25;

   public void anonymousClassTest() {

       final Integer[] localAreaVar = {25};

       //Anonymous class

       ActionListener listener = new ActionListener() {

           @Override

           public void actionPerformed(ActionEvent e) {

               //class variables without final may be used

               classAreaVar2 = classAreaVar2 + 25;

               //local variables cannot be used if they are not final;

               /*Local variable is accessed from within inner class: needs to be declared final */

               localAreaVar[0] = localAreaVar[0] +5;

           }

       };

   }

}

44. How is any custom class related to the Object class?

All classes are descendants of the Object superclass. It is not necessary to specify explicitly. As a result, an Object o object can refer to an object of any other class.

45. Tell us about each of the methods of the Object class.

  • public final native Class getClass ()  – returns the class of this object in runtime.
  • public native int hashCode () – returns hash code
  • public boolean equals (Object obj) – compares objects.
  • protected native Object clone () throws CloneNotSupportedException – object cloning
  • public String toString () – returns a string representation of the object.
  • public final native void notify ()  – one stream wakes up, which waits on the “monitor” of this object.
  • public final native void notifyAll ()  – all threads that are waiting on the “monitor” of this object are awakened.
  • public final native void wait (long timeout) throws InterruptedException – the thread goes into standby mode for the specified time.
  • public final void wait () throws InterruptedException  – causes this thread to wait until another thread calls the notify () or notifyAll () methods for this object.
  • public final void wait (long timeout, int nanos) throws InterruptedException  – causes this thread to wait until another thread calls notify () or notifyAll () for this method, or until a specified period of time has elapsed.
  • protected void finalize () throws Throwable  – called by the garbage collector when the garbage collector has determined that the object is no longer referenced.

46. ​​What is the equals () method. How it differs from the operation ==.

47. If you want to override equals (), which conditions must be satisfied for the overridden method?

47. If equals () is overridden, are there any other methods that should be overridden?

49. What are the features of the hashCode and equals methods? How are the hashCode and equals methods implemented in the Object class? What rules and conventions exist to implement these methods? When do they apply?

This is a method defined in Object that is used to compare objects. When comparing objects with == there is a comparison on the links. When comparing equals () , a comparison is made according to the states of the objects (the implementation of the equals method for the newly created class falls on the shoulders of the developers). From the point of view of mathematics, equals () denotes the equivalence relation of objects. Equivalent is a relation that is symmetric, transitive, and reflexive.

  • Reflexivity : for any nonzero x, x.equals (x) returns true;
  • Transitivity : for any non-zero x, y and z, if x.equals (y) and y.equals (z) returns true, then x.equals (z) returns true;
  • Symmetry: for any non-zero x and y, x.equals (y) should return true if and only if y.equals (x) returns true .
  • Also for any non-zero x, x.equals (null) should return false

When overriding equals (), you must override the hashCode () method. Equal objects must return the same hash codes.

A hash code is a number. More specifically, it is a fixed-length bit string obtained from an array of arbitrary length. In Java terms, a hash code is the integer result of the method, to which an object is passed as an input parameter.

This method is implemented in such a way that for the same input object, the hash code will always be the same. It should be understood that the set of possible hash codes is limited to the primitive type int , and the set of objects is limited only by our imagination. Hence the following statement: “The set of objects is more powerful than the set of hash codes”. Due to this limitation, it is quite possible that the hash codes of different objects may coincide.

The main thing here is to understand that:

  • If the hash codes are different, then the input objects are guaranteed to be different.
  • If the hash codes are equal, then the input objects are not always equal.

The situation when different objects have the same hash codes is called a collision. The likelihood of a collision depends on the hash code generation algorithm used.

Advanced Java OOPS Interview Questions And Answers

50. Which method returns a string representation of an object?

someObject. toString () ;

51. What happens if you redefine equals without overriding hashCode? What problems may arise?

Violate the contract. Classes and methods that used the rules of this contract may not work correctly. So for the HashMap object, this may lead to the fact that the pair that was placed in the Map may not be found in it when accessing the Map if a new key instance is used.

52. Are there any recommendations on which fields should be used when calculating hashCode?

Those used in determining the method equals(). The hash code should be evenly distributed over the area of ​​possible received values.

53. What do you think, will there be any problems if the object that is used as a key in hashMap has a field that participates in the definition of hashCode?

Will be. When accessing the key, we can not find the value.

54. What is the difference between an abstract class and an interface, in which cases what will you use?

Abstract classes are used only when there is an “is a” type of relationship; interfaces can be implemented by classes that are not related to each other.

An abstract class can implement methods; The interface can implement static methods starting from version 8.

The interface can describe constants and methods. All interface methods are public (abstract) and abstract (default), and fields are public static final. With java 8, in interfaces you can implement default and static methods.

In Java, a class can be inherited (implemented) from many interfaces, but only from a single abstract class.

With abstract classes, you lose the individuality of the class that inherits it; with interfaces, you simply extend the functionality of each class.

55. Is it possible to access private class variables and, if so, how?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

public class SomeClass {

   private String name = “SomeNameString”;

   private Integer x = 25;

}

public class TestPrivateAccess {

   public static void main(String[] args) {

       SomeClass someClass = new SomeClass();

       try {

           Field reflectField = SomeClass.class.getDeclaredField(“name”); //NoSuchFieldException e

           Field reflectField2 = SomeClass.class.getDeclaredField(“x”); //NoSuchFieldException e

           /* Если не дать доступ, то будет ошибка

           java.lang.IllegalAccessException: Class .. .TestPrivateAccess

           can not access a member of class .. .SomeClass with modifiers “private”

           */

           reflectField.setAccessible(true);

           reflectField2.setAccessible(true);

           String fieldValue = (String) reflectField.get(someClass); //IllegalAccessException ex

           Integer fieldValue2 = (Integer) reflectField2.get(someClass); //IllegalAccessException ex

           System.out.println(reflectField);//private java.lang.String ru.javastudy.interview.oop.privateFieldAccess.SomeClass.name

           System.out.println(fieldValue); //SomeNameString

           System.out.println(reflectField2);//private java.lang.Integer ru.javastudy.interview.oop.privateFieldAccess.SomeClass.x

           System.out.println(fieldValue2); //25

       } catch (NoSuchFieldException e) {

           e.printStackTrace();

       } catch (IllegalAccessException ex) {

           ex.printStackTrace();;

       }

   }

}

56. What is volatile and transient? For what and in what cases it would be possible to use default?

volatile   – the cache is not used (meaning the memory area in which the JVM can store a local copy of the variable in order to reduce the time to access the variable) when accessing the field. For a volatile variable, the JVM guarantees synchronization for read / write operations, but does not guarantee for operations to change the value of a variable.

transient – an indication that during serialization / deserialization this field does not need to be serialized / deserialized.

Technical OOPS Java Interview Questions

57. Expanding modifiers for inheritance, overriding and hiding methods. If the parent class has a method declared as private, can the heir expand its visibility? And if protected? And narrow visibility?

There is a general principle: you can expand the visibility, you can not narrow. private  methods are visible only inside the class; for descendants they are not visible. Therefore, they can not be expanded.

58. Does it make sense to declare the method private final?

No, such a method is not so visible to the heirs, and therefore cannot be redefined by them.

59. What are the features of the initialization of final variables?

  • For the field. A field marked with the word final cannot change its value after initialization.
  • A non-static final field can be initialized: in the description, in the constructor (in all), in the static block, in the dynamic block.
  • The static final field (static final) is initialized either in a static block or in the description.
  • The value of local variables, as well as method parameters marked with the word final, cannot be changed after assignment.

60. What happens if a single class constructor is declared final?

The final keyword is not applicable to the constructor .

61. What is finalize? Why is it needed? What can you tell about the garbage collector and the algorithms of its work.

The finalize () method is called before the object is removed by the garbage collector (garbage collector, hereinafter  referred to as gc ). There are many different implementations of gc . The basis of the work is as follows:  gc marks the objects that other objects no longer refer to to delete them. Then on one of the passes the marked objects are deleted.

The finalize () call is not guaranteed, because An application can be completed before another garbage collection is started. Yes, you can cancel the assembly of the object using the finalize () method , assigning its link to some static method.

62. Why is the clone method declared protected? What is needed to implement cloning?

This indicates that although the method is in the Object  class and the developer wants to use it, it must be redefined. To do this, you must implement the Clonable interface to honor the contract.

Must Read Java Interview Questions Books

RELATED INTERVIEW QUESTIONS

  1. Core Java Interview Questions
  2. JSF Interview Questions
  3. JSP Interview Questions
  4. JPA Interview Questions
  5. Spring Framework Interview Questions
  6. Spring Boot Interview Questions
  7. Core Java Multiple Choice Questions
  8. 60 Java MCQ Questions And Answers
  9. Aricent Java Interview Questions
  10. Accenture Java Interview Questions
  11. Advanced Java Interview Questions For 5 8 10 Years Experienced
  12. Core Java Interview Questions For Experienced
  13. GIT Interview Questions And Answers
  14. Network Security Interview Questions
  15. CheckPoint Interview Questions
  16. Page Object Model Interview Questions
  17. Apache Pig Interview Questions
  18. Python Interview Questions And Answers
  19. Peoplesoft Integration Broker Interview Questions
  20. PeopleSoft Application Engine Interview Questions
  21. RSA enVision Interview Questions
  22. RSA SecurID Interview Questions
  23. Archer GRC Interview Questions
  24. RSA Archer Interview Questions
  25. Blockchain Interview Questions
  26. Commvault Interview Questions
  27. Peoplesoft Admin Interview Questions
  28. ZooKeeper Interview Questions
  29. Apache Kafka Interview Questions
  30. Couchbase Interview Questions

 

Leave a Reply

Your email address will not be published. Required fields are marked *