Topic 6.2: Working with Methods and Encapsulation - Apply the static keyword to methods and fields Flashcards
How are static fields different from instance fields?
Static fields belong to the class itself and are shared among all instances, while instance fields have separate copies for each object (instance) of a class.
How do you invoke a static method in Java?
to perform this, you use the class name followed by the method name, without creating an instance of the class.
For example, MathUtils.addNumbers(5, 10)
What is the concept of
static methods
in Java?
These belong to the class itself rather than an instance of the class.
What are static methods in Java used for?
These are used for utility operations or computations that are independent of any specific object’s state, such as:
- performing calculations
- converting values
- providing common functionality shared among all instances of a class.
When are static fields initialized?
Static fields are initialized when the class is loaded into memory, typically before any objects of the class are created.
These belong to the class itself rather than an instance of the class.
What is the concept of
static methods
in Java?
These are used for utility operations or computations that are independent of any specific object’s state, such as:
- performing calculations
- converting values
- providing common functionality shared among all instances of a class.
What are static methods in Java used for?
Why are static fields used in Java?
Static fields are used to store data or state that is common to all objects of a class or is not specific to any individual instance, such as constants, configuration settings, or global counters.
How do you define a static method in Java?
syntax for this:
access_modifier static return_type method_name(parameter_list) { // method body }
syntax for this:
access_modifier static return_type method_name(parameter_list) { // method body }
How do you define a static method in Java?
What is the effect when static fields are modified?
in this case the modification will be reflected across all instances of the class
in this case the modification will be reflected across all instances of the class
What is the effect when static fields are modified?
Can static methods access instance variables or invoke instance methods?
No, static methods cannot directly access instance variables or invoke instance methods. They can only access other static members directly.
How are static fields accessed in Java?
Static fields can be accessed using the class name followed by the field name, without the need to create an instance of the class.
to perform this, you use the class name followed by the method name, without creating an instance of the class.
For example, MathUtils.addNumbers(5, 10)
How do you invoke a static method in Java?