When we can have class and method as static? [closed] - java

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
When we can have class and method as static?
Anybody please help me with some example...

When you don't need a class instance to invoke that method. It means that method does not depend on any non-static members of the class

You can make a method static if it doesn't use any non-static members of the class.
You can make a class static if it only contains static members.

If a method doesn't change it's behaviour based on different objects of it's enclosing class. it can be marked static.
Check Math class. all of it's methods are static cause, their behaviour just depends on the argument within methods and those methods don't make any change in the class states.
All the utility/helper methods can be (should be) marked as static. i.e. if their behaviour is same for all objects, why to have different copy for each object, just have one copy and let all objects share same copy.
You should check this also: Why are you not able to declare a class as static in Java?

A static method belongs to the Class and thus not to a specific instance. If you think at programming languages in term of message dispatching we can say procedural programming provides only 1 level of message dispatching as the name of the function correspond to its actual behavior. In Object Oriented Programming we have two level of message dispatching as you also has you have to specify an object plus the signature of a function (method). The same function may behave differently on different object depending on their status (subClass overridden method, etc.). A static method is instead like a global function you can execute where and how you want and always has the same behavior.
You may therefore limit the usage of static methods although there are cases in which they are helpful. In the Singleton pattern (http://it.wikipedia.org/wiki/Singleton) a static method is necessary to retrieve the Singleton's instance (also a private static attribute is necessary to keep track of it).
For those who claim Singleton are evil and you should always use Dependency Injection via Google Guice, also Guice relies on static method for instance to create an injector (http://lowcoupling.wordpress.com/2012/12/05/dependency-injection/).
So I guess the best answer is you should always think if the problem you are facing might just be solved by the injection of object but there are cases in which the usage of static methods is pretty reasonable.

Related

Why can't we create an object with the "this" keyword in java? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I've seen places where object creation factories are implemented by having a reference to the class object and having a create method which does this:class.newInstance(), which uses reflection, and might not be efficient compared to calling the default constructor directly.
If java supported something like return new this();, I could implement this in a parent class and that would work as a factory method (and would throw an exception if there is no such constructor as does class.newInstance()).
Why isn't such a thing supported?
PS: My first question in stackOverflow :)
As designed, the this keyword is valid only in the context of an instance. Its type is the type of the class within which it occurs.
From the Java Language Specification:
When used as a primary expression, the keyword this denotes a value that is a reference to the object for which the instance method was invoked (§15.12), or to the object being constructed.
If you want to create a new object using the default constructor, you can call it directly.
return new MyType();
If you want to create a clone of an object, you may be able to use the Object.clone() method.
You can get close using this.getClass().newInstance()
However, this approach is not recommended. For one thing, it requires that the class has a default constructor.
according to java doc
Within an instance method or a constructor, this is a reference to the
current object — the object whose method or constructor is being
called. You can refer to any member of the current object from within
an instance method or a constructor by using this.
So this is holding the current instance of object. it is not a type.
But when you are initializing a object you need to initialize it with the class type. like
ClassType c = new ClassType();
So these two things are totally different. that's why you can't initialize with this
I think it's because when you use "this" means that the object is already created, so you cannot use "new this" to create another.
Answer to your question is how could you create the instance of a class without knowing class name ? however this keyword is applicable to current object which you have not created yet.

Does the System.out object belong to class System or class PrintStream? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I'm new to programming and I just started learning Java. I'm curious that does the object System.out belong to class System or class PrintStream?
I referred to a textbook, JAVA CONCEPTS 4/e. The textbook states that to use the out object in the System class, you must refer it as System.out but later in the book it states that the System.out belongs to class PrintStream.
I've searched google and stackoverflow but all the answers are too hard for me to understand.
"out" belongs to class "System" and is of type "PrintStream" :)
It depends what you mean by "belongs to".
Usually, people would say out "belongs" to System because it is a static field declared in that class. Note, though, that this concept of belonging is only a weak one, basically implying only a namespace ownership. There is no special relation between a class and its static fields.
You may also say the object referred to by the out variable belongs to the PrintStream class because it is an instance of that class (or a subclass), just as "beagle" belongs to the "dog" class. This is not standard usage in Java parlance, but it makes perfect sense from the perspective of type theory, where a type is really a set of values, and the value of out "belongs" to that the type / set defined by the PrintStream class.
System.out is a PrintStream object. It is defined in System (so, it is member of System) class as :
static PrintStream out
See: http://docs.oracle.com/javase/6/docs/api/java/lang/System.html
It is defined as:
static PrintStream out
out is a static field in System. Its type is PrintStream.
In loose simple terms, 'out' is a field (i.e. an object) in class 'System' of type 'PrintStream'.
Out is the static reference variable in class System and is of PrintStream(class) type.

Private, Protected, Public and me confused [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
What is the benefit of using public private protected keywords in method declarations?
I can imagine the benefit of public private protected keywords for variables because it will prevent unnecessary "value change" by objects outside the particular class
but I cannot imagine the benefit of putting the keyword "private" or "public" or "protected" in method declarations.
If there is a method, it is my belief that the only object(s) that can use the method is the object that contains that method anyways?
First of all, let's clarify the meaning of public, protected, package, and private access. In each case, you are correct that an object must exist to use a non-static method. However, these keywords indicate who is allowed to invoke the method on the object:
public methods can be invoked by anyone.
protected methods can be invoked by any class in the same package or subclasses in other packages.
package private methods (without any access modifier) can be only invoked by classes in the same package.
private methods can be invoked only by the same class.
As an example, I often use private methods to factor out code which is otherwise repeated among several different methods. This code isn't part of the public interface for other classes to use. Rather, it is a "worker" method that does some of the calculations internal to the class itself.
public means the method can be override, and is available for use by any code for which the enclosing class is visible.
private means the method is usable only by the enclosing class.
protected means that the method is callable only by the enclosing class, and any class that extends that class.
package (no keyword before the method) means that the method can be called by any code within a class in the same package as the enclosing class.
In Java, difference between default, public, protected, and private
These different keywords are useful in designing how your class will be used. public methods are part of the "contract" you are exposing to the users of your class. private methods are typically implementation code that should not be exposed in any way to the outside world because you want to hide that logic in case you want to replace or modify it in the future without breaking your "contract" with the class' users.
protected methods are available to classes that extend your class. So maybe there's some implementation that you want to make available for overriding -- or perhaps you need an extending class to implement this method in order to make your class work, but it's not part of the "contract" your exposing to callers of your class or those calling the extending class.
Use package to create implementation code that other classes in the package can call, but that you don't want to expose to those using your class (not part of your "contract" with your users.) I use package level methods if I need to test some tricky implementation code from a unit test, but don't want to make the method public.
To understand the benefit of restricting access to a method, consider this : You can safely change or even remove a private method from a class, because you know it's only ever accessed from within that class. If you are publishing an API, and you expose a public method, then its out there for good. If you try to change it, you will break code that relys on it being available. You have to think about how code will evolve over time to fully appreciate this.
If there is a method, it is my belief that the only object(s) that can
use the method is the object that contains that method anyways?
No, not true. Methods can be declared static, which means they do not require an object to be invoked on.

Can someone explain what is a HelperClass and what does in Java or in C++? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I want to know what the HelperClass used for. Can someone please explain it with examples?
Thank You
A helper class (in Java, at least) is usually just a static utility class with a variety of methods. In general, a single helper class deals with related functionality, like Apache Commons' StringUtils class, that has a bunch if static methods that operate on strings.
In Java, these types of classes often exist to wrap up functionality that either cannot (for example, the String class is final, so additional functionality can't be added) or should not be addedto the class itself.
In a nutshell, however, a helper class is a class that helps, by providing general or specific functionality in a generic, reusable, encapsulated way.
It's usually used to preserve the cohesion of a class (in Java). Useful methods that don't really belong in any of the classes context can be put in a helper class (static of course) so you can call them.
They are usually static methods. They dont belong to a class or a context of the class, but instead using a class, you can provide some sort of functionality with a helper class/ static classes.
Informal way of referring to Utility Class

Singleton and Static Utility classes [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
What factors influence the appropriate design pattern to use?
Clarification:
The reason I ask this question is because I'm designing an application that requires multiple static factory classes and singleton manager classes. At times, I become confused as to which design I should employ and I thought asking this community why and when may help clarify things for me a bit.
Singleton is used when a single object needs to be instantiated and all requested object access goes through this particular instance. This object can maintain state if desired.
Static Utility is used when you have a class that is just stateless utility functions.. it does not maintain state. An instance of the object is never instantiated.
I use static utility classes for shared functions that will be called from many different contexts - e.g. maths functions similar to those in java.util.Math. This is an appropriate pattern assuming that these are "pure" functions (i.e. don't manipulate any state or access any data other than than the parameters they are given).
I very rarely use singletons, and in particular try to avoid global singletons. They suffer from all the usual problems associated with global variables. They make testing difficult, and unless your singleton is also immutable they introduce problems of global state. The main place I have found them useful is in performance hacks that depend on object identity - for example:
public static final END_OF_SEQUENCE_MARKER=new EndMarker();
Then when traversing a sequence you can just test if (object==END_OF_SEQUENCE_MARKER). Because it's a static final reference, the JIT will turn this into an extremely fast test....
EDIT
Having just seen your clarification, some quick extra comments:
Static factory classes don't usually make sense. The whole point of a factory class is that you can instantiate it (or a subclass!), make some configuration changes on the factory object, then use it to generate object instances according to the configuration that you need. If you're going to make it static, you might as well just create a static MyObject.create(..) method rather than having a whole static MyObjectFactory class....
Likewise, why have a separate singleton manager class? Usually the best class to manage the singleton is the singleton class itself, since you will typically need it to access a private constructor, assuming you want to guarantee that only one instance will ever be created. Just having a simple static MySingleton.getInstance() method will usually do everything that you need.
IMO static utility classes chalk down a concrete contract between the caller and the class. This is different than singletons wherein you can change the implementation behind the scenes to make your so called 'singleton' provider hand out a new instance each time a call to getInstance is made.
So yes, basically use static utility methods when you are damn sure (e.g. Math) you'd never need an instance and use singletons when you think that a single instance is good enough for the time being but might change in the future (e.g. connection providers).
I'm not sure what the question is here.
Singleton patterns are used where the instance has state that may be preserved or altered across a number of calls - this might be a connection pool or some other shared object that the class provides access to.
Static utility classes are used where each individual method is stateless, and has no bearing on the other methods that the class provides.

Categories