What is the purpose of the static keyword in
Java?
The static keyword is used to declare class-level variables and methods. They
belong to the class rather than instances of the class and can be accessed
using the class name.
can we use the static keyword for package
level access?
In Java, the static keyword is not used for
controlling access levels. The static keyword is primarily used to
define class-level members, such as variables and methods, that are associated
with the class itself rather than with instances of the class. The concept of
access levels, on the other hand, is controlled by access modifiers.
public class MyClass {
public static int
publicStaticVariable = 10;
static int packagePrivateStaticVariable
= 20; // package-private by default
private static int
privateStaticVariable = 30;
}
To summarize, while static is used to define
class-level members, access modifiers (public, protected, default, private) are
used to control the visibility and accessibility of those members. The use of static
and access modifiers is independent of each other.
It's important to note that while static members have
their use cases, they should be used judiciously, as overuse of static members
can lead to code that is tightly coupled and less maintainable.
Instance-specific members (non-static) are more common in object-oriented
programming, where each object has its state and behavior.
does instance of the classes are non-static?
Instances of a class are non-static. When we create
objects (instances) of a class in Java, each object has its own set of instance
variables and instance methods. These are attributes and behaviour’s that are
specific to each individual object.
Comments
Post a Comment