Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Comments on What are the disadvantages of using static methods in Java?
Parent
What are the disadvantages of using static methods in Java?
I was using static method few moments ago. But I noticed that I was returning a variable using that static method. According to the article,
Static is a keyword that identifies the class-related thing. It means the given Method or variable is not instance-related but Class related. It can be accessed without creating the instance of a Class.
I think I can access the static method without caring of class, isn't it? Is there something special of static method? static method can helps to decrease amount of source code. So Is it better to use static method? Or is there any limit of it?
Post
If it were always better to use static
, the language would have been designed to always assume static
, or at least default to static
. That the language defaults to making methods not static indicates that the designers of the programming language envisioned static methods to be rare.
Java is intended to be an object oriented programming language, where a program is a set of objects that "talk" to each other using methods. Objects are created from classes, and classes can be related through inheritance. Specifically, a class can be declared to extend another class, which allows it to inherit or override methods from the parent class. For instance:
class Animal {
void move() {
System.out.prinln("The animal moves");
}
}
class Dog extends Animal {
@Override
void move() {
System.out.println("The dog walks");
}
}
class Snake extends Animal {
@Override
void move() {
System.out.println("The snake slithers");
}
}
Which you can then use as follows:
Animal animal = new Snake();
animal.move(); // "The snake slithers"
So even though the variable contains an Animal
, that Animal
knows whether it is a Dog
or a Snake
, and responds accordingly when it is asked to move
.
This ability to refine the behavior of a class in a subclass is very useful. However, since this depends on the type of the object, it is only available for methods of objects, not static methods.
By using static, you deny yourself this useful tool. This may seem a small price to pay when your programs are tiny and consist only of a few isolated methods. However, once your programs get bigger, and particularly once they start incorporating code written by other people, the ability to refine code they have written will be invaluable.
1 comment thread