Hi i have a web service in java, in which i have a class that has different methods that modify the string that the client sends and return it back according to the type of sting he wants. So based on the string type requirement a method is called..
like
class Test{
public static String a(String z)
{
// do stuff and return;
}
public static String b(String z)
{
// do stuff and return;
}
}
so if an array of like 10000 requests comes, these methods are called 10000 times, i want to know that should these methods be taken as static or NOT(i should create a global object of this class in my main web service class and call these methods) ?
I don't think you need to make method as static, if you can access the method within the object then you should (avoid static as much as possible).This improve code performance (in terms of memory utilization).
What's the compelling reason that these methods be static? If you need static methods, then create those. Otherwise, from a design standpoint, stick to non-static methods. You can't override static methods (though you can hide 'em.)
And there's this:
In Java, is there any disadvantage to static methods on a class?
You can use a static method if the method behaves the same for all cases. If the methods just does some work on the string supplied as a parameter and the behavior is the same for all instances, you can.
Again, you can also make a singleton out of it & call the methods through the UNIQUE_INSTANCE.
Something like:
public class Test {
private static final Test UNIQUE_INSTANCE = new Test();
private Test() {
}
public static final Test getUniqueInstance() {
return UNIQUE_INSTANCE;
}
public final String a(String z) {
// do stuff and return;
}
public final String b(String z) {
// do stuff and return;
}
}
Then you can do >>
Test.getUniqueInstance().a("Hello");
Test.getUniqueInstance().b("World");
If there is not any resource which is shared among the threads then there is not harm to use any static method.
Yes, there should be a Static modifier since there is no interaction between the different methods or functions, and the result is returned in the very same method. the "Static" word is to define a class variable or method that can be accessed without instantiating an object of such class.
if you do not intend to instantiate the class, and just need to use the methods inside, "Static" is the correct way to go, and set the class constructor to private.
Related
I was facing an error before, but when I made an object in this class the and called for the method, it worked flawlessly. Any explanation? Do I always have to make an object to call for methods outside of the main method (but in the same class)?
here:
public class A{
public static void main(String[] args){
A myObj= new A();
System.out.println(myObj.lets(2));
}
public int lets(int x){
return x;
}
}
You need to understand static. It associates a method or field to the class itself (instead of a particular instance of a class). When the program starts executing the JVM doesn't instantiate an instance of A before calling main (because main is static and because there are no particular instances of A to use); this makes it a global and an entry point. To invoke lets you would need an A (as you found), or to make it static (and you could also limit its' visibility) in turn
private static int lets(int x) {
return x;
}
And then
System.out.println(lets(2));
is sufficient. We could also make it generic like
private static <T> T lets(T x) {
return x;
}
and then invoke it with any type (although the type must still override toString() for the result to be particularly useful when used with System.out.println).
There are a importance concept to consider an is static concept. In your example you have to create an instance of your class because the main method is static and it only "operate" with other statics methods or variable. Remember that when you instantiate a class you are creating a copy of that class an storing that copy in the instance variable, so as the copy (That was create inside of a static method in your case) is also static so it can access the method which is not static in that context.
In order to not create an instance and access to your method you need to make your lets method static(due to the explanation abode)
public static int lets(int x){
return x;
}
And in your main you don't need to instantiate the class to access to this method.
public static void main(String[] args){
System.out.println(lets(2));
}
Check this guide about static in java: https://www.baeldung.com/java-static
Hope this help!
I'm learning Java and I just wonder why public and private is used when a method or members is static? When static is used they are class methods and class members and could be used from other classes without creating an object, so is public and private necessary? Some help is preciated to understand. Sorry if this question is too simple for some.
The accessibility of a field or method is orthogonal to the fact that it's static or not.
You could have a static method accessible from the outside, and a static method that must only be used from inside the class itself (by other static or non-static methods). The same goes for fields.
For example:
// not visible from the outside
private static final long MILLISECONDS_IN_A_MINUTE = 1000L * 60 * 60;
public static Date addMinutes(Date d, int amount) {
return addMillis(d, MILLISECONDS_IN_A_MINUTE * amount);
}
// not visible from the outside
private static Date addMillis(Date d, long amount) {
return new Date(d.getTime() + amount);
}
It's not necessary, but there can be static methods and data members for internal use only.
An example for this is if you want an unique id for every instance of the class:
class Foo
{
private static int nextId = 0;
private static int generateId() { return ++nextId; }
private int id;
public Foo()
{
id = generateId();
}
}
As you can see, nextId and generateId() are not needed outside the class, nor should they be used outside the class. The class itself is responsible for generating id's. But you need them to be static (well, you need nextId to be static, but you can also make generateId() static since it doesn't access non-static members).
Whenever an object Foo is created, the static counter is incremented, thus you get different ids for each instance of the class. (this example is not thread-safe)
Suppose you have a static public method and this method must access to a private attribute. This private attribute must be static too. There's one reason why private static exists.
Example :
public class Test {
private static int myattr = 0;
public static void foo() {
myattr = 2;
}
}
Above, myattr must be a static attribute in order to use it in the foo() method.
Yes it is needed.
If you have a Static Method and want to use a private variables in that method, then you need to declare it static too.
Or you want the static variables not be visible to other packages, then don't declare it public.
From what I remember, it's not really needed. But public means, basically in any programming language, that it can be used by outside files. With private it can only be used within that file, and static means you cannot change the value of said reference. Whether these be functions, or variables, the same rules apply. I might be off. Haven't done Java in about a year and a half.
The ways you can incorporate these types is up to you. After all, a program is only as diverse as it's user. ^_^
Public and private keywoards have to do with visibility: which members do you want to accessible to other classes and which should be hidden or encapsulated.
Static members relate to the class as a whole, while non-static members operate on object instances.
I'm learning Java and I just wonder why public and private is used when a method or members is static?
I believe your question is due to a common misconception that the access modifiers are for instances, but they're not!
Two different instances can access each others private members if they are of the same class.
In other words, the access modifiers works on class level. Since also static members belong to some class, it makes sense to have access modifiers also on them.
A static method (or variable) that should only be used by code in the same class (as in the example by JB Nizet) should be private, while a static method or variable that may be used by code in any class should be public.
When the static is used with methods it doesn't only mean that it should be used by the members of other classes.
The case when we access the static methods of a class is one when
the class (which contains the method) cannot be instantiated i.e. no objects can be created of that class.
There may be situations when two different classes may have static methods with same name. In that case you want to use the method of the same class not the method of other class.
At present I have a class that is calling the static method of a different class. What I am trying to do however is have the static method change a variable of the calling class, is that possible?
Example code:
public class exClass {
private int aVariable;
public exClass() {
othClass.aMethod();
}
}
public class othClass {
static void aMethod() {
// stuff happens, preferably stuff that
// allows me to change exClass.aVariable
}
}
So what I would like to know is, if there is a way to access aVariable of the instance of exClass that is calling othClass. Other than using a return statement, obviously.
Not if aClass doesn't expose that variable. This is what encapsulation and information hiding are about: if the designer of the class makes a variable private, then only the component that owns it can modify or access it.
Of course, the dirty little secret in Java is that reflection can get you around any private restriction.
But you should not resort to that. You should design your classes appropriately and respect the designs of others.
You can pass this as a parameter to the second function.
public class exClass {
public int aVariable;
public exClass()
{
othClass.aMethod(this);
}
}
public class othClass{
static void aMethod(exClass x)
{
x.aVariable = 0; //or call a setter if you want to keep the member private
}
}
you should gave the static method in othClass the instance of exClass like othClass.aMethod(this), then you can change the variable of that instance, or make the variable static if you dont need an instance
I have a method in my static state machine that is only used once when my application is first fired up. The method needs to be public, but I still want it hidden. Is there a way to use an annotation or something that will hide the method from the rest of the project?
You cannot make a public method hidden (unless you can declare it private). You can however put in a subclass and only let the users of the object know the type of the superclass, that is:
class A {
//Externally visible members
}
class B extends A {
//Secret public members
}
Then you instantiate the class B, but only let the type A be known to others...
Once you declare public method it becomes part of your class's contract. You can't hide it because all class users will expect this method to be available.
You could use package level instead of public. That way it can only be called by your application.
If a method is public, it can't be hidden. What you may really be looking for is just a way to restrict access to calling a method. There are other ways to achieve a similar effect.
If there are some things that your state machine does that are "only used once when my application is first fired up" it sounds a lot like those are things that could happen in the constructor. Although it depends on how complex those tasks are, you may not want to do that at construction time.
Since you said your state machine is static, is it also a Singleton? You could maybe use the Singleton Pattern.
public class SimpleStateMachine {
private static SimpleStateMachine instance = new SimpleStateMachine();
private SimpleStateMachine() {
super();
System.out.println("Welcome to the machine"); // prints 1st
}
public static SimpleStateMachine getInstance() {
return instance;
}
public void doUsefulThings() {
System.out.println("Doing useful things"); // prints 3rd
}
}
Here's some code for a client of this Singleton:
public class MachineCaller {
static SimpleStateMachine machine = SimpleStateMachine.getInstance();
public static void main(String... args) {
System.out.println("Start at the very beginning"); // prints 2nd
machine.doUsefulThings();
}
}
Note that the SimpleStateMachine instance isn't built until the first time your class is accessed. Because it's declared as static in the MachineCaller client, that counts as a "first access" and creates the instance. Keep this tidbit in mind if you definitely want your state machine to perform some of those initialization tasks at the time your application starts up.
So, if you don't want to turn your state machine class into a true singleton... you can use a static initialization block do your one-time tasks the first time the class is accessed. That would look something like this:
public class SimpleStateMachine {
static {
System.out.println("First time tasks #1");
System.out.println("First time tasks #2");
}
public SimpleStateMachine() {
super();
System.out.println("Welcome to the machine");
}
public void doUsefulThings() {
System.out.println("Doing useful things");
}
}
While we're at it, since you mentioned that it's a state machine... the Head First Design Patterns book does a nice, easily understandable treatment of the State Pattern. I recommend reading it if you haven't already.
The idiomatic approach to doing this is to use interfaces to limit the visibility of your methods.
For example, say you have the following class:
public class MyClass {
public void method1() {
// ...
}
public void method2() {
// ...
}
}
If you want to limit some parts of the project to only see method1(), then what you do is describe it in an interface, and have the class implement that interface:
public interface Method1Interface {
public void method1();
}
...
public class MyClass implements Method1Interface {
public void method1() {
// ...
}
public void method2() {
// ...
}
}
Then, you can limit the visibility of the methods by choosing to pass the class around either as a MyClass reference, or as a Method1Interface reference:
public class OtherClass {
public void otherMethod1(MyClass obj) {
// can access both obj.method1() and obj.method2()
}
public void otherMethod2(Method1Interface obj) {
// can only access obj.method1(), obj.method2() is hidden.
}
}
A bonus of this approach is that it can also be easily extended. Say, for example, you now also want to independently control access to method2(). All you need do is create a new Method2Interface along the same lines as Method1Interface, and have MyClass implement it. Then, you can control access to method2() in exactly the same manner as method1().
This is a similar approach to that advocated in #MathiasSchwarz's answer, but is much more flexible:
The independent access control described in the preceding paragraph isn't possible with Mathias' technique, due to Java not supporting multiple inheritance.
Not requiring an inheritance relationship also allows more flexibility in designing the class hierarchy.
The only change required to the original class is to add implements Method1Interface, which means that it is a very low-impact refactor since existing users of MyClass don't have to be changed at all (at least, until the choice is made to change them to use Method1Interface).
An alternative solution: You can make it private and create a invokeHiddenMethod(String methodName, Object ... args) method using reflection.
You said that your public method is used only once when the application is started up.
Perhaps you could leave the method public, but make it do nothing after the first call?
There is a (non-)keyword level package level visibility. Instead of public, protected, or private, you use nothing.
This would make the method or class visible to the class and others in the package, but would give you a certain modicum of privacy. You may want to look at What is the use of package level protection in java?.
Hmm... You want a private method, but want to access it outside?
Try do this with reflection.
http://download.oracle.com/javase/tutorial/reflect/index.html
I have seen many Java programmers do something like this:
public static void main(String args[]) {
new MyClass();
}
So basically they create just one object of the class. If there is a method which should run only once, I guess this approach can achieve that. Your method will be called from inside the constructor. But since I don't know how your app works, what are the constraints, so it is just a thought.
Hello
What use is the final modifier on a method/constructor parameter?
Ex:
class someClass {
private final double some; // I understand the use of final in this context, immutability etc..
public someClass(final double some) {
// I don't understand what purpose is served by making "some" final
this.some = some;
}
public void someMethod(final double some) {
// I don't understand what purpose is served by making "some" final
}
}
There are 2 main situations when you need it:
1) you want to use the parameter inside local class (usually, anonymous class), like:
public void foo(final String str) {
Printer p = new Printer() {
public void print() {
System.out.println(str);
}
};
p.print();
}
2) you like the style when every variable which is not modified is marked with the final word (it is generally a good practice to keep as much things immutable as possible ).
Well, the purpose is that you cannot asign the parameter with anything
public someClass(T some) {
some = null; //You can do this. Maybe you want to use the variable `some` later on in your constructor
}
public someClass(final T some) {
some = null; //You can't do this. If you want to reuse `some` you can't.
}
Useful? Not much. Normally you don't use arguments variables. But in some special situations you may want to be able to do it.
Anyway, if some does new someClass(mySome) , mySome will never be changed although inside the function you assign values to the argument. There is no such thing as pass-by-refrence in Java. Variables are primitives or references to objects, never the object itself.
From the point of view of the function, the some variable is a constant.
Another benefit would be to prevent variable reuse. That is to say "some" should be used for only one purpose.