Câu hỏi phỏng vấn Java
Câu hỏi

What does the static keyword mean? Can you override private or static method in Java?

Câu trả lời

Understanding the Static Keyword in Java

The static keyword in Java is used to indicate that a particular field, method, or block belongs to the type itself, rather than to instances of the type. This means that the static member can be accessed without creating an instance of the class. Static members are shared among all instances of the class, making them useful for implementing constants or methods that are common to all instances.

  • Static Variables: These are also known as class variables. They are declared with the static keyword in a class, but outside a method, constructor, or a block.

  • Static Methods: These methods can be called without creating an object of the class. They can only directly call other static methods and can only access static data.

  • Static Blocks: Blocks of code inside a class that are surrounded by braces and preceded by the static keyword. These blocks are executed when the class is loaded into the JVM, before the creation of any object and even before the invocation of any static method.

Overriding Private or Static Methods in Java

  1. Private Methods: These methods cannot be overridden because they are not visible outside the class they belong to. Even if a subclass defines a method with the same name and signature as a private method in its superclass, the subclass’s method is a completely new method; it does not override the superclass’s method.

  2. Static Methods: Overriding is based on dynamic method dispatch, which is only applicable to instance methods. Static methods are bonded statically at compile time and do not depend on a particular instance for their invocation. Therefore, static methods cannot be overridden. If a subclass defines a static method with the same signature as a static method in its superclass, it hides the superclass’s method rather than overriding i...

junior

junior

Gợi ý câu hỏi phỏng vấn

middle

If an object reference is set to null , will the Garbage Collector immediately free the memory held by that object?

middle

What differences exist between Iterator and ListIterator ?

middle

What is a Constructor, Constructor Overloading and Copy-Constructor in Java ?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào