So I am calling a method defined in the main method of the same class. I am referencing the callable method using 'this' keyword. Why cannot I call this non-static method, as shown below, in static main method?
Relevant but a little different question, by choice of design, would it make sense to construct a separate class for implementing logic. Essentially, main class should only have a main method to keep things simple. Any ideas will be appreciated.
UniqueChars.java:8: non-static variable this cannot be referenced from a static context
System.out.println(this.hasAllUniqueChars(input));
^
1 error
public class UniqueChars {
boolean hasAllUniqueChars(String input) {
return false;
}
public static void main(String[] args) {
String input = "Harry";
System.out.println(this.hasAllUniqueChars(input));
}
}
Because this is non-static. this is an instance, and you cannot reference instance variables within a static method since static means "one for the entire class."
You should make the hasAllUniqueChars method static (like static boolean hasAllUniqueChars(String input)), so you could do
System.out.println(UniqueChars.hasAllUniqueChars(input));
Or just (since you're already in the class)
System.out.println(hasAllUniqueChars(input));
You could also keep it non-static, and do this:
UniqueChars uc = new UniqueChars();
System.out.println(uc.hasAllUniqueChars(input));
You can only use "this" within an instance of an object.
So you either need to make a UniqueChars object, or you need to make hasAllUniqueChars static
Because there's no this in a static method, because this refers to the current instance (e.g., an instantiated object of that class).
There's no instance for static methods: that's why they're called static methods. They live at the class level, and are not associated with any instance.
You should either (a) create an instance and call the instance method on it, or (b) make the method static and don't bother. If the class doesn't need any instance-specific state, might as well make it static, e.g., a utility method.
Use this code:
System.out.println(new UniqueChars().hasAllUniqueChars(input));
Method hasAllUniqueChars is not static. To make it static you have to put static before name boolean like static boolean hasAllUniqueChars. Static methods don't need instances to be able to call them. So you would call it as UniqueChars.hasAllUniqueChars().
if you don't want method to be static then you would need to create new instance of UniqueChars class and then call it. new UniqueChars().hasAllUniqueChars() as others have pointed out.
Either construct an instance of the class that has the main method (possibly in main() itself), and invoke the method on it.
System.out.println(new UniqueChars().hasAllUniqueChars(input));
Or make hasAllUniqueChars() a static method.
Within an instance method or a constructor, this is a reference to the current object, which is non-static. You can't use non-static instance to static method.
Related
I was just reading over the text given to me in my textbook and I'm not really sure I understand what it is saying. It's basically telling me that static methods or class methods include the "modifier" keyword static. But I don't really know what that means?
Could someone please explain to me in really simple terms what Static or Class Methods are?
Also, could I get a simple explanation on what Instance methods are?
This is what they give me in the textbook:
There are important practical implications of the presence or absence of the static modifier. A public class method may be invoked and executed as soon as Java processes the definition of the class to which it belongs. That is not the case for an instance method. Before a public instance method may be invoked and executed, an instance must be created of the class to which it belongs. To use a public class method, you just need the class. On the other hand, before you can use a public instance method you must have an instance of the class.
The manner in which a static method is invoked within the definition of another method varies according to whether or not the two methods belong to the same class. In the example above, factorial and main are both methods of the MainClass class. As a result, the invocation of factorial in the definition of main simply references the method name, "factorial".
The basic paradigm in Java is that you write classes, and that those classes are instantiated. Instantiated objects (an instance of a class) have attributes associated with them (member variables) that affect their behavior; when the instance has its method executed it will refer to these variables.
However, all objects of a particular type might have behavior that is not dependent at all on member variables; these methods are best made static. By being static, no instance of the class is required to run the method.
You can do this to execute a static method:
MyClass.staticMethod(); // Simply refers to the class's static code
But to execute a non-static method, you must do this:
MyClass obj = new MyClass(); //Create an instance
obj.nonstaticMethod(); // Refer to the instance's class's code
On a deeper level the compiler, when it puts a class together, collects pointers to methods and attaches them to the class. When those methods are executed it follows the pointers and executes the code at the far end. If a class is instantiated, the created object contains a pointer to the "virtual method table", which points to the methods to be called for that particular class in the inheritance hierarchy. However, if the method is static, no "virtual method table" is needed: all calls to that method go to the exact same place in memory to execute the exact same code. For that reason, in high-performance systems it's better to use a static method if you are not reliant on instance variables.
Methods and variables that are not declared as static are known as instance methods and instance variables. To refer to instance methods and variables, you must instantiate the class first means you should create an object of that class first.For static you don't need to instantiate the class u can access the methods and variables with the class name using period sign which is in (.)
for example:
Person.staticMethod(); //accessing static method.
for non-static method you must instantiate the class.
Person person1 = new Person(); //instantiating
person1.nonStaticMethod(); //accessing non-static method.
Difference between Static methods and Instance methods
Instance method are methods which require an object of its class to be created before it can be called. Static methods are the methods in Java that can be called without creating an object of class.
Static method is declared with static keyword. Instance method is not with static keyword.
Static method means which will exist as a single copy for a class. But instance methods exist as multiple copies depending on the number of instances created for that class.
Static methods can be invoked by using class reference. Instance or non static methods are invoked by using object reference.
Static methods can’t access instance methods and instance variables directly. Instance method can access static variables and static methods directly.
Reference : geeksforgeeks
Static methods, variables belongs to the whole class, not just an object instance. A static method, variable is associated with the class as a whole rather than with specific instances of a class. Each object will share a common copy of the static methods, variables. There is only one copy per class, no matter how many objects are created from it.
Instance methods => invoked on specific instance of a specific class. Method wants to know upon which class it was invoked. The way it happens there is a invisible parameter called 'this'. Inside of 'this' we have members of instance class already set with values. 'This' is not a variable. It's a value, you cannot change it and the value is reference to the receiver of the call.
Ex: You call repairmen(instance method) to fix your TV(actual program). He comes with tools('this' parameter). He comes with specific tools needed for fixing TV and he can fix other things also.
In static methods => there is no such thing as 'this'.
Ex: The same repairman (static method). When you call him you have to specify which repairman to call(like electrician). And he will come and fix your TV only. But, he doesn't have tools to fix other things (there is no 'this' parameter).
Static methods are usually useful for operations that don't require any data from an instance of the class (from 'this') and can perform their intended purpose solely using their arguments.
In short, static methods and static variables are class level where as instance methods and instance variables are instance or object level.
This means whenever a instance or object (using new ClassName()) is created, this object will retain its own copy of instace variables. If you have five different objects of same class, you will have five different copies of the instance variables. But the static variables and methods will be the same for all those five objects. If you need something common to be used by each object created make it static. If you need a method which won't need object specific data to work, make it static. The static method will only work with static variable or will return data on the basis of passed arguments.
class A {
int a;
int b;
public void setParameters(int a, int b){
this.a = a;
this.b = b;
}
public int add(){
return this.a + this.b;
}
public static returnSum(int s1, int s2){
return (s1 + s2);
}
}
In the above example, when you call add() as:
A objA = new A();
objA.setParameters(1,2); //since it is instance method, call it using object
objA.add(); // returns 3
B objB = new B();
objB.setParameters(3,2);
objB.add(); // returns 5
//calling static method
// since it is a class level method, you can call it using class itself
A.returnSum(4,6); //returns 10
class B{
int s=8;
int t = 8;
public addition(int s,int t){
A.returnSum(s,t);//returns 16
}
}
In first class, add() will return the sum of data passed by a specific object. But the static method can be used to get the sum from any class not independent if any specific instance or object. Hence, for generic methods which only need arguments to work can be made static to keep it all DRY.
If state of a method is not supposed to be changed or its not going to use any instance variables.
You want to call method without instance.
If it only works on arguments provided to it.
Utility functions are good instance of static methods. i.e math.pow(), this function is not going to change the state for different values. So it is static.
The behavior of an object depends on the variables and the methods of that class. When we create a class we create an object for it. For static methods, we don't require them as static methods means all the objects will have the same copy so there is no need of an object.
e.g:
Myclass.get();
In instance method each object will have different behaviour so they have to call the method using the object instance.
e.g:
Myclass x = new Myclass();
x.get();
Static Methods vs Instance methods
Constructor:
const Person = function (birthYear) {
this.birthYear = birthYear;
}
Instance Method -> Available
Person.prototype.calcAge = function () {
2037 - this.birthYear);
}
Static Method -> Not available
Person.hey = function(){
console.log('Hey')
}
Class:
class PersonCl {
constructor(birthYear) {
this.birthYear = birthYear;
}
/**
* Instance Method -> Available to instances
*/
calcAge() {
console.log(2037 - this.birthYear);
}
/**
* Static method -> Not available to instances
*/
static hey() {
console.log('Static HEY ! ');
}
}
The static modifier when placed in front of a function implies that only one copy of that function exists. If the static modifier is not placed in front of the function then with every object or instance of that class a new copy of that function is made. :)
Same is the case with variables.
I have the following code:
private static AppWidgetService mInstance = null;
public static void startRefresh() {
AppWidgetProvider.setRefreshingState(mInstance
.getApplicationContext());
AppWidgetManager.refreshHandler(mInstance.getApplicationContext());
}
It sometimes fails in runtime, and sometimes passes.
for the obviuse exception:
cannot call a non-static method from a static context
I'm confused as mInstance is static,
so its instance methods could be called from a static context. no?
then how come if sometimes fails?
From a static function, you can call only static function or use static variable. The linking is done at run time. So, though your compilation will be fine but at run time it will fail when call is made. Try making your function non static if you want to make that call.
OR
The only way to call a non-static method from a static method is to have an instance of the class containing the non-static method. By definition, a non-static method is one that is called ON an instance of some class, whereas a static method belongs to the class itself.
This problem arises when you call a static method from a non-static block/method. In your code both 'setRefreshingState()' and 'refreshHandler()' are static methods. To call theses methods you have to remove static from your method definition.
Can anyone please explain me why it is illegal for static method to invoke a non static method?
A non-static method is an instance method which acts upon a specific instance (object), and has access to that object's members. A static method is not associated with a specific instance.
It is legal to call a non-static method if you provide an instance:
class Foo
{
public static void f()
{
instanceMethod(); // Not OK - no instance provided.
this.instanceMethod(); // Not OK - no "this" in static methods.
new Foo().instanceMethod(); // OK because you provide an instance
}
public void instanceMethod() {}
}
because to call static method you don't need object of class, where to call non static method you need,
Static method is associated with class where non static method is associated with state (Object)
A non-static method is a method that executes in the context of an instance . Without an instance it makes no sense to call one, so the compiler prevents you from doing so - ie it's illegal.
If a method doesn't access any instance fields (aka instance variables) then it should probably be changed to be a static method.
non static methods have the implicit parameter this which static methods have not (because there is no this)
Alone because of this fact it would not be possible to call non-static methods form static ones.
Static methods belong to the class. Non static methods belong to an instance.
The non static method require an instance (this) to be executed on. The static method don't require any instance, since the class itself is the instance to which it belongs.
If I have 100 object instance, every nonStatic() method invocation affects the state of a different object. So every nonStatic method is 'different' because it acts on different entities.
At the same time, even if I have 100 instance of an object, calling staticMethod() doesn't affect any of those instances, because it can only affect the static members of the class.
There is 1 class and 1 instance of every static methods or static member variables.
For the non static members we have every single method associated to the class instance.
So if you would be able to call the nonStatic method, from a static method, which of the 100 instance would be affected? You see: it doesn't make sense.
Static methods are connected with the class.
Regular methods are connected to the object.
In static method there is no object on which you can run the non-static method.
It is not illegal to call a non-static method from a static method. Whenever you invoke a static method there is no need of an instance of a class whereas in case of non-static case you do.
I was just reading over the text given to me in my textbook and I'm not really sure I understand what it is saying. It's basically telling me that static methods or class methods include the "modifier" keyword static. But I don't really know what that means?
Could someone please explain to me in really simple terms what Static or Class Methods are?
Also, could I get a simple explanation on what Instance methods are?
This is what they give me in the textbook:
There are important practical implications of the presence or absence of the static modifier. A public class method may be invoked and executed as soon as Java processes the definition of the class to which it belongs. That is not the case for an instance method. Before a public instance method may be invoked and executed, an instance must be created of the class to which it belongs. To use a public class method, you just need the class. On the other hand, before you can use a public instance method you must have an instance of the class.
The manner in which a static method is invoked within the definition of another method varies according to whether or not the two methods belong to the same class. In the example above, factorial and main are both methods of the MainClass class. As a result, the invocation of factorial in the definition of main simply references the method name, "factorial".
The basic paradigm in Java is that you write classes, and that those classes are instantiated. Instantiated objects (an instance of a class) have attributes associated with them (member variables) that affect their behavior; when the instance has its method executed it will refer to these variables.
However, all objects of a particular type might have behavior that is not dependent at all on member variables; these methods are best made static. By being static, no instance of the class is required to run the method.
You can do this to execute a static method:
MyClass.staticMethod(); // Simply refers to the class's static code
But to execute a non-static method, you must do this:
MyClass obj = new MyClass(); //Create an instance
obj.nonstaticMethod(); // Refer to the instance's class's code
On a deeper level the compiler, when it puts a class together, collects pointers to methods and attaches them to the class. When those methods are executed it follows the pointers and executes the code at the far end. If a class is instantiated, the created object contains a pointer to the "virtual method table", which points to the methods to be called for that particular class in the inheritance hierarchy. However, if the method is static, no "virtual method table" is needed: all calls to that method go to the exact same place in memory to execute the exact same code. For that reason, in high-performance systems it's better to use a static method if you are not reliant on instance variables.
Methods and variables that are not declared as static are known as instance methods and instance variables. To refer to instance methods and variables, you must instantiate the class first means you should create an object of that class first.For static you don't need to instantiate the class u can access the methods and variables with the class name using period sign which is in (.)
for example:
Person.staticMethod(); //accessing static method.
for non-static method you must instantiate the class.
Person person1 = new Person(); //instantiating
person1.nonStaticMethod(); //accessing non-static method.
Difference between Static methods and Instance methods
Instance method are methods which require an object of its class to be created before it can be called. Static methods are the methods in Java that can be called without creating an object of class.
Static method is declared with static keyword. Instance method is not with static keyword.
Static method means which will exist as a single copy for a class. But instance methods exist as multiple copies depending on the number of instances created for that class.
Static methods can be invoked by using class reference. Instance or non static methods are invoked by using object reference.
Static methods can’t access instance methods and instance variables directly. Instance method can access static variables and static methods directly.
Reference : geeksforgeeks
Static methods, variables belongs to the whole class, not just an object instance. A static method, variable is associated with the class as a whole rather than with specific instances of a class. Each object will share a common copy of the static methods, variables. There is only one copy per class, no matter how many objects are created from it.
Instance methods => invoked on specific instance of a specific class. Method wants to know upon which class it was invoked. The way it happens there is a invisible parameter called 'this'. Inside of 'this' we have members of instance class already set with values. 'This' is not a variable. It's a value, you cannot change it and the value is reference to the receiver of the call.
Ex: You call repairmen(instance method) to fix your TV(actual program). He comes with tools('this' parameter). He comes with specific tools needed for fixing TV and he can fix other things also.
In static methods => there is no such thing as 'this'.
Ex: The same repairman (static method). When you call him you have to specify which repairman to call(like electrician). And he will come and fix your TV only. But, he doesn't have tools to fix other things (there is no 'this' parameter).
Static methods are usually useful for operations that don't require any data from an instance of the class (from 'this') and can perform their intended purpose solely using their arguments.
In short, static methods and static variables are class level where as instance methods and instance variables are instance or object level.
This means whenever a instance or object (using new ClassName()) is created, this object will retain its own copy of instace variables. If you have five different objects of same class, you will have five different copies of the instance variables. But the static variables and methods will be the same for all those five objects. If you need something common to be used by each object created make it static. If you need a method which won't need object specific data to work, make it static. The static method will only work with static variable or will return data on the basis of passed arguments.
class A {
int a;
int b;
public void setParameters(int a, int b){
this.a = a;
this.b = b;
}
public int add(){
return this.a + this.b;
}
public static returnSum(int s1, int s2){
return (s1 + s2);
}
}
In the above example, when you call add() as:
A objA = new A();
objA.setParameters(1,2); //since it is instance method, call it using object
objA.add(); // returns 3
B objB = new B();
objB.setParameters(3,2);
objB.add(); // returns 5
//calling static method
// since it is a class level method, you can call it using class itself
A.returnSum(4,6); //returns 10
class B{
int s=8;
int t = 8;
public addition(int s,int t){
A.returnSum(s,t);//returns 16
}
}
In first class, add() will return the sum of data passed by a specific object. But the static method can be used to get the sum from any class not independent if any specific instance or object. Hence, for generic methods which only need arguments to work can be made static to keep it all DRY.
If state of a method is not supposed to be changed or its not going to use any instance variables.
You want to call method without instance.
If it only works on arguments provided to it.
Utility functions are good instance of static methods. i.e math.pow(), this function is not going to change the state for different values. So it is static.
The behavior of an object depends on the variables and the methods of that class. When we create a class we create an object for it. For static methods, we don't require them as static methods means all the objects will have the same copy so there is no need of an object.
e.g:
Myclass.get();
In instance method each object will have different behaviour so they have to call the method using the object instance.
e.g:
Myclass x = new Myclass();
x.get();
Static Methods vs Instance methods
Constructor:
const Person = function (birthYear) {
this.birthYear = birthYear;
}
Instance Method -> Available
Person.prototype.calcAge = function () {
2037 - this.birthYear);
}
Static Method -> Not available
Person.hey = function(){
console.log('Hey')
}
Class:
class PersonCl {
constructor(birthYear) {
this.birthYear = birthYear;
}
/**
* Instance Method -> Available to instances
*/
calcAge() {
console.log(2037 - this.birthYear);
}
/**
* Static method -> Not available to instances
*/
static hey() {
console.log('Static HEY ! ');
}
}
The static modifier when placed in front of a function implies that only one copy of that function exists. If the static modifier is not placed in front of the function then with every object or instance of that class a new copy of that function is made. :)
Same is the case with variables.
My Assumptions:
Static method cannot cannot call non-static methods.
Constructors are kind of a method with no return type.
Given this example...
public class Main {
public static void main(String[] args) {
Main p = new Main(); // constructor call
k(); // [implicit] `this` reference
}
protected Main() {
System.out.print("1234");
}
protected void k() {
}
}
this line prints 1234: Main p = new Main()
this line throws an Exception: k()
Why did the example code do those two things? Don't they conflict with my above Assumptions? Are my Assumptions correct?
1 - Static method cannot cannot call non-static methods.
Sure they can, but they need an object to call the method on.
In a static method, there's no this reference available, so foo() (which is equivalent to this.foo()) is illegal.
2 - Constructors are kind of a method with no return type.
If they should be compared to methods, I would say constructors are closer to non-static methods (since there is indeed a this reference inside a constructor).
Given this view, it should be clear to you why a static method can call a constructor without any problems.
So, to sum it up:
Main p = new Main();
is okay, since new Main() does not rely on any existing object.
k();
is not okay since it is equivalent to this.k() and this is not available in your (static) main method.
No. Constructors aren't ordinary methods in this respect. The whole point of the constructor is to, well, construct a new instance of the class.
So it can be invoked in static scope too. Just think about it: if you needed an existing instance of your class in order to create a new instance of it, you would simply never be able to instantiate it ever.
A few clarifications:
Static method cannot cannot call non-static methods.
Not quite. You can call a nonstatic method from inside a static method, just you need to scope it to a specific object of that class. I.e.
p.k();
would work perfectly in your code sample above.
The call
k();
would be fine inside an instance (nonstatic) method. And it would be equivalent to
this.k();
The implied this refers to the current instance of the class. Whenever the compiler sees an unqualified call like k() within an instance method, it will automatically scope it with this. . However, since static methods aren't tied to any instance of the class, you (and the compiler) can't refer to this inside a static method. Hence you need to explicitly name an instance of the class to call an instance method on.
Rules are simple:
1 - Static method cannot cannot call non-static methods.
That's simply not true. A static method can call a non-static method, just via a "target" reference. For example, this is fine in a static method:
Integer x = Integer.valueOf(10);
int y = x.intValue(); // Instance method!
The real point is "there's no this reference within a static method".
2 - Constructors are kind of a method with no return type.
That's not a really useful model, to be honest. It makes more sense (from the caller's point of view) to consider a constructor as a static method with a return type that's the same as the declaring class, but even that's not a perfect model by any means.
I suggest you think of a constructor as a different type of member. Embrace the differences between constructors and methods, instead of trying to hide them.