Can I use methods of a class without instantiating

2019-03-14 10:25发布

I have a class with several methods and there is no constructor among these methods.

So, I am wondering if it is possible to call a method of a class without a creation of an instance of the class.

For example, I can do something like that:

NameOfClass.doMethod(x1,x2,...,xn)

In general I do not see why it should be impossible. I just call a function which does something (or return some values). If it is possible, what will happen if the method sets a value for a private variable of the class. How can I reach this value? In the same way?

NameOfClass.nameOfVariable

11条回答
beautiful°
2楼-- · 2019-03-14 10:49

That would be static methods.

查看更多
疯言疯语
3楼-- · 2019-03-14 10:54

It's called static variables and static methods. Just try it and see that it compiles.

查看更多
倾城 Initia
4楼-- · 2019-03-14 10:56

As many have pointed out: This is only possible if the method is static. Maybe some OOP background is in order: A method should always belong to a class. So what is the use of calling a method without an instance of a class? In a perfect OO world there shouldn't be any reason to do that. A lot of use cases that have to do with static methods talk about assigning some kind of identity to your class. While this is perfectly reasonable in a programming world it isn't very convincing when it comes to object oriented design.

As we program in an imperfect world there is often a use case for a "free function" (The way Java or C++ implement sort() for example). As Java has no direct support for free functions classes with only static "methods" are used to express those semantics with the added benefit of the class wrapper providing a "namespace". What you think of this workaround and if you see it as a flaw in language design is IMO a matter of opinion.

查看更多
三岁会撩人
5楼-- · 2019-03-14 10:59

I have a class with several methods and there is no constructor among these methods.

If you don't explicitly define a constructor then you get a default constructor provided by the compiler. So if those methods aren't static, try this:

NameOfClass x = new NameOfClass();
x.doMethod(x1,x2,...,xn);
查看更多
Explosion°爆炸
6楼-- · 2019-03-14 11:00

If the methods are static, yes.

But you won't be able to access non-static members.

查看更多
爱情/是我丢掉的垃圾
7楼-- · 2019-03-14 11:00

In proper encapsulation, you should not "see" what is happening upon instanciation. To rely on a class's lack of a constructor is breaking this form. The designed of the class my have in mind to add formal state initialization in the constructor at a later date. Your "contract" with the class is only that you can use the methods as they are currently designed.

If you desire to use the functionality of that method without the class overhead, maybe it best for you to include that method in your existing "client" class (of course this is just "copy and paste" coding and is considered an anti-pattern of of software design.

查看更多
登录 后发表回答