As I understand static, it is that static methods can be called without an instance of the object needing to exist. So instead of making an object and calling the method on that object, you can just call the method on the class.
Now, I have a class Main that has the following object: public ScribbleCanvas myCanvas;. In the ScribbleCanvas class I would like to access a method of the Main-class.
Now, since there is already an instance of Main (since this called the ScribbleCanvas), how can I access a non-static method of this class? Or perhaps the better question - where is the error in my reasoning?
You could have a constructor or a setter for the ScribbleCanvas that takes a parameter as the current instance of Main.
ScribbleCanvas sc = new ScribbleCanvas(this);
or
sc.setMainClass(this);
And with those, you just reference a field to the parameter.
You can set Main instance as a member of myCanvas and use it.
The below code explains how you should do it. The testInstanceMethod is been taken as an
example for an instance method in Main class. This method should be accessible as well
public class ScribbleCanvas{
private Main mainObject = null;
public ScribbleCanvas(){
this.mainObject = new Main();
//Call instance method in mainObject (member instance)
this.mainObject.testInstanceMethod();
}
public void setMainObject(Main arg){
this.mainObject = arg;
}
public Main getMainObject(){
return this.mainObject;
}
}
For invoking static methods, you can directly put the Classname and invoke using DOT operator like Main.testStaticMethod() provided the method is accessible as well
Disclaimer : NOT tested / compiled
If I understand your question you want to:
Have an instance of the Main class, let's call it myMain.
The instance will have an instance of the ScribbleCanvas class, called myCanvas
From the ScribbleCanvas instance (myCanvas) have access to methods within myMain.
In order to do this you can:
Declare a member of type Main within ScribbleCanvas, say callingMain
Include a parameter of type Main (say paramMain) in the constructor for ScribbleCanvas
In the constructor, store paramMain in callingMain
From Main, pass in this to the constructor
Within your code, you can refer to callingMain.method()
Does this help?
Related
This question already has answers here:
Difference between Static methods and Instance methods
(10 answers)
Closed 4 years ago.
Whenever I have to call a method from another class, I first create an object and then call it through the object. But while I was writing some code, I mistakenly wrote classname.methodname(); and it worked.
I would usually write,
classname obj = new classname();
obj.methodname();
Here is the actual code:
Class 1
public class Dataset {
public static List<ECCardData> getDataset() {
//Code
}
in Class 2
List<ECCardData> dataset = Dataset.getDataset();
I noticed that the methodname() was static. Was that the reason?
Yes, for static methods (with suitable access modifier) you can call directly with your class by
YourClass.yourMethod();
and this way, too
YourClass anObject = new YourClass();
anObject.yourMethod();
Happy coding.
I hate answering my question, but I found the correct answer.
When a method is declare static, only one instance of that method will exist. When you create an object a new instance of the method is created, which is not possible for a static method. Therefore you use the class name.
classname.methodname(); //only one instance
classname obj;
obj.methodname(); //instance with obj as Object(IDE gives warning, should not be allowed, ideally)
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:
classname.staticMethod();//Simply refers to the class's static code But
> to execute a non-static method, you must do this:
>
> classname obj = new classname();//Create an instance
> obj.nonstaticMethod();//Refer to the instance's class's code
public class TestClass(){
public static void main(String []args) {
TestClass t1 = new TestClass();
t1.anything();
}
}
Is it not strange to create a object in the definition of same class? Because then in response - this object creates a new object, then this new object creates another, and the infinite loop begins to never end until the memory is full.
Is it not strange to create an object in the definition of the same class
than in response the object create a new object then this new object
create another and the infinite loop begins
No, the main method only runs once when you run your program. It will not be executed again. So, the object will be created only once.
Think of your main method to be outside your class. Which creates an instance of your class, and uses the instance created. So, when you create an instance from main method, the constructor is invoked to initialize the state of your instance, and then when the constructor returns, the next statement of your main method is executed.
Actually, you can consider main method not to be a part of the state of the instance of your class.
However, had you created the instance of your class inside your constructor (say 0-arg), and the reference as instance reference variable, then that will turn into an infinite recursion.
public class A {
private A obj;
public A() {
obj = new A(); // This will become recursive creation of object.
// Thus resulting in StackOverflow
}
}
You would only have an infinite loop (stack overflow error) if you tried to do the below:
public class TestClass {
public TestClass() {
TestClass t = new TestClass();
}
}
And elsewhere, you try to create an object of the class TestClass.
public class TestClass{
public static void main(String []args) {
TestClass t1 = new TestClass();
t1.anything();
}
}
This is a perfectly valid code. When the main method is called, no prior instance of the TestClass exists (it needs not, because the main method is static).
public class Test2{
public Test2 clone(){
return new Test2();
}
}
This is perfectly valid as well. When you create a new instance of Test2, it contains the clone method, but the method is not automatically executed. Only when the clone method is called, one more instance of Test2 is created.
public class MyLinkedList{
MyLinkedList next;
MyLinkedList(int elems){
if(elems>0){
next = new MyLinkedList(elems-1);
}else{
next = null;
}
}
}
is perfectly valid as well, even if the constructor creates a new instance using the same constructor, because the creation is guarded by a conditional, so creating an instance sometimes triggers a new creation.
public class Fail{
public Fail(){
new Fail();
}
}
Is the only problematic example here. The compiler doesn't complain. It can be translated into byte code and it can be executed. At the runtime, however, you cause a stack overflow:
a new Fail is allocated
its no-arg constructor is called
the constructor tries to create a new Fail
a new Fail is allocated
its no-arg constructor is called
...
The compiler allows this, because, in general, the compiler cannot prevent all infinite recursion. The compiler allows anything that can be translated into bytecode.
The compiler, however, may issue a warning if it detects a method or a method chain calls itself unconditionally.
It's not really odd. All object oriented languages that I am aware of allow this. The code is semantically part of the object definition, but in practice it can be considered separate from the actual state of any given object. So there is no loop because object construction doesn't call your method (unless, of course, it does - then you have a problem).
When you use new to create object constructors are called which initializes the instance variable this happens till all the constructors of your super class have been called .
if you put the some code inside constructor that will run each time you create an object
When a program starts it executes the main method. In java you cannot create a method outside of a class. All methods must be encapsulated within a class. Therefore the main method as an entry point to the program must be within a class. When you run this program the main method will be run once and will execute the code inside it. In your case it creates an object of the enclosing class TestClass. This does not have to happen. It can create objects outside of this class as well. You will only get an infinite loop as explained in the #adarshr's answer.
It's not strange at all. You see, the main() method is the starting point of execution. So figuratively, java is "blind" (doesn't see what you've told it to execute/run) unless it has "seen" the main() method. It's after "seeing" the main() method that it now has the ability to execute other instructions that follow, so as a takeaway, the main() method literally doesn't belong to the object inside it's own class in the first place.
And for the recursion, it will only occur when you do something like what #Rohit Jain stated. Or per your code, you don't invoke anything but you rather invoke the main() itself.
public static void main(String []args) {
TestClass t1 = new TestClass();
main(String[] args);
}
}
The reference variable t1 literally didn't invoke main because it's static. And the nice thing is that, main isn't invoked by your code rather the "jvm", so sensu stricto, you can't remove the static from there. It'll cause some good error message explicitly telling you that the static is supposed to be there. That's why you see main() not invoked by the object in the above snippet.
If you do one these then recursion will occur other than that, you are safe to create an object inside it's own class. Albeit, I wouldn't recommend that. Let one class have the main() method and instantiate (create object) other classes inside that Main class (the class that contain the main method). That way you get to run the code once.
I'm learning java and now i've the following problem: I have the main method declared as
public static void main(String[] args) {
..... }
Inside my main method, because it is static I can call ONLY other static method!!! Why ?
For example: I have another class
public class ReportHandler {
private Connection conn;
private PreparedStatement prep;
public void executeBatchInsert() { ....
} }
So in my main class I declare a private ReportHandler rh = new ReportHandler();
But I can't call any method if they aren't static.
Where does this go wrong?
EDIT: sorry, my question is: how to 'design' the app to allow me to call other class from my 'starting point' (the static void main).
You simply need to create an instance of ReportHandler:
ReportHandler rh = new ReportHandler(/* constructor args here */);
rh.executeBatchInsert(); // Having fixed name to follow conventions
The important point of instance methods is that they're meant to be specific to a particular instance of the class... so you'll need to create an instance first. That way the instance will have access to the right connection and prepared statement in your case. Just calling ReportHandler.executeBatchInsert, there isn't enough context.
It's really important that you understand that:
Instance methods (and fields etc) relate to a particular instance
Static methods and fields relate to the type itself, not a particular instance
Once you understand that fundamental difference, it makes sense that you can't call an instance method without creating an instance... For example, it makes sense to ask, "What is the height of that person?" (for a specific person) but it doesn't make sense to ask, "What is the height of Person?" (without specifying a person).
Assuming you're leaning Java from a book or tutorial, you should read up on more examples of static and non-static methods etc - it's a vital distinction to understand, and you'll have all kinds of problems until you've understood it.
Please find answer:
public class Customer {
public static void main(String[] args) {
Customer customer=new Customer();
customer.business();
}
public void business(){
System.out.println("Hi Harry");
}
}
Java is a kind of object-oriented programming, not a procedure programming. So every thing in your code should be manipulating an object.
public static void main is only the entry of your program. It does not involve any object behind.
So what is coding with an object? It is simple, you need to create a particular object/instance, call their methods to change their states, or do other specific function within that object.
e.g. just like
private ReportHandler rh = new ReportHandler();
rh.<function declare in your Report Handler class>
So when you declare a static method, it doesn't associate with your object/instance of your object. And it is also violate with your O-O programming.
static method is usually be called when that function is not related to any object behind.
You can't call a non-static method from a static method, because the definition of "non-static" means something that is associated with an instance of the class. You don't have an instance of the class in a static context.
A static method means that you don't need to invoke the method on an instance. A non-static (instance) method requires that you invoke it on an instance. So think about it: if I have a method changeThisItemToTheColorBlue() and I try to run it from the main method, what instance would it change? It doesn't know. You can run an instance method on an instance, like someItem.changeThisItemToTheColorBlue().
More information at http://en.wikipedia.org/wiki/Method_(computer_programming)#Static_methods.
You can think of a static member function as one that exists without the need for an object to exist. For example, the Integer.parseInt() method from the Integer class is static. When you need to use it, you don't need to create a new Integer object, you simply call it. The same thing for main(). If you need to call a non-static member from it, simply put your main code in a class and then from main create a new object of your newly created class.
You cannot call a non-static method from the main without instance creation, whereas you can simply call a static method.
The main logic behind this is that, whenever you execute a .class file all the static data gets stored in the RAM and however, JVM(java virtual machine) would be creating context of the mentioned class which contains all the static data of the class.
Therefore, it is easy to access the static data from the class without instance creation.The object contains the non-static data
Context is created only once, whereas object can be created any number of times.
context contains methods, variables etc. Whereas, object contains only data.
thus, the an object can access both static and non-static data from the context of the class
Since you want to call a non-static method from main, you just need to create an object of that class consisting non-static method and then you will be able to call the method using objectname.methodname();
But if you write the method as static then you won't need to create object and you will be able to call the method using methodname(); from main. And this will be more efficient as it will take less memory than the object created without static method.
Useful link to understand static keyword
https://www.codeguru.com/java/tij/tij0037.shtml#Heading79
I have a class named Media which has a method named setLoanItem:
public void setLoanItem(String loan) {
this.onloan = loan;
}
I am trying to call this method from a class named GUI in the following way:
public void loanItem() {
Media.setLoanItem("Yes");
}
But I am getting the error
non-static method setLoanItem(java.lang.String) cannot be referenced from a static context
I am simply trying to change the variable onloan in the Media class to "Yes" from the GUI class.
I have looked at other topics with the same error message but nothing is clicking!
Instance methods need to be called from an instance. Your setLoanItem method is an instance method (it doesn't have the modifier static), which it needs to be in order to function (because it is setting a value on the instance that it's called on (this)).
You need to create an instance of the class before you can call the method on it:
Media media = new Media();
media.setLoanItem("Yes");
(Btw it would be better to use a boolean instead of a string containing "Yes".)
setLoanItem is an instance method, meaning you need an instance of the Media class in order to call it. You're attempting to call it on the Media type itself.
You may want to look into some basic object-oriented tutorials to see how static/instance members work.
setLoanItem() isn't a static method, it's an instance method, which means it belongs to a particular instance of that class rather than that class itself.
Essentially, you haven't specified what media object you want to call the method on, you've only specified the class name. There could be thousands of media objects and the compiler has no way of knowing what one you meant, so it generates an error accordingly.
You probably want to pass in a media object on which to call the method:
public void loanItem(Media m) {
m.setLoanItem("Yes");
}
You need to correctly separate static data from instance data. In your code, onLoan and setLoanItem() are instance members. If you want to reference/call them you must do so via an instance. So you either want
public void loanItem() {
this.media.setLoanItem("Yes");
}
or
public void loanItem(Media object) {
object.setLoanItem("Yes");
}
depending on how you want to pass that instance around.
I'm beginning to program in Java.
public static void main(String[]args)
A book said that I should use static in this case, but doesn't clearly say why I should or what it means.
Could you clarify this?
The concept of static has to do with whether something is part of a class or an object (instance).
In the case of the main method which is declared as static, it says that the main method is an class method -- a method that is part of a class, not part of an object. This means that another class could call a class method of another class, by referring to the ClassName.method. For example, invoking the run method of MyClass would be accomplished by:
MyClass.main(new String[]{"parameter1", "parameter2"});
On the other hand, a method or field without the static modifier means that it is part of an object (or also called "instance") and not a part of a class. It is referred to by the name of the specific object to which the method or field belongs to, rather than the class name:
MyClass c1 = new MyClass();
c1.getInfo() // "getInfo" is an instance method of the object "c1"
As each instance could have different values, the values of a method or field with the same name in different objects don't necessarily have to be the same:
MyClass c1 = getAnotherInstance();
MyClass c2 = getAnotherInstance();
c1.value // The field "value" for "c1" contains 10.
c2.value // The field "value" for "c2" contains 12.
// Because "c1" and "c2" are different instances, and
// "value" is an instance field, they can contain different
// values.
Combining the two concepts of instance and class variables. Let's say we declare a new class which contains both instance and class variables and methods:
class AnotherClass {
private int instanceVariable;
private static int classVariable = 42;
public int getInstanceVariable() {
return instanceVariable;
}
public static int getClassVariable() {
return classVariable;
}
public AnotherClass(int i) {
instanceVariable = i;
}
}
The above class has an instance variable instanceVariable, and a class variable classVariable which is declared with a static modifier. Similarly, there is a instance and class method to retrieve the values.
The constructor for the instance takes a value to assign to the instance variable as the argument. The class variable is initialized to be 42 and never changed.
Let's actually use the above class and see what happens:
AnotherClass ac1 = new AnotherClass(10);
ac1.getInstanceVariable(); // Returns "10"
AnotherClass.getClassVariable(); // Returns "42"
Notice the different ways the class and instance methods are called. The way they refer to the class by the name AnotherClass, or the instance by the name ac1. Let's go further and see the behavioral differences of the methods:
AnotherClass ac1 = new AnotherClass(10);
AnotherClass ac2 = new AnotherClass(20);
ac1.getInstanceVariable(); // Returns "10"
AnotherClass.getClassVariable(); // Returns "42"
ac2.getInstanceVariable(); // Returns "20"
AnotherClass.getClassVariable(); // Returns "42"
As can be seen, an instance variable is one that is held by an object (or "instance"), therefore unique to that particular instance, which in this example is the objects referred to by ac1 and ac2.
A class variable on the other hand is only unique to that entire class. To get this point across even better, let's add a new method to the AnotherClass:
public int getClassVariableFromInstance() {
return classVariable;
}
Then, run the following:
AnotherClass ac1 = new AnotherClass(10);
AnotherClass ac2 = new AnotherClass(20);
ac1.getInstanceVariable(); // Returns "10"
ac1.getClassVariableFromInstance(); // Returns "42"
ac2.getInstanceVariable(); // Returns "20"
ac2.getClassVariableFromInstance(); // Returns "42"
Although getClassVariableFromInstance is an instance method, as can be seen by being invoked by referring to the instances ac1 and ac2, they both return the same value, 42. This is because in both instance methods, they refer to the class method classVariable which is unique to the class, not to the instance -- there is only a single copy of classVariable for the class AnotherClass.
I hope that some what clarifies what the static modifier is used for.
The Java Tutorials from Sun has a section called Understanding Instance and Class Members, which also goes into the two types of variables and methods.
Please see a nice description on Wikipedia
For example, notice how in the Math class, you can say things like
Math.Abs(x);
without having to say
Math m = new Math();
These are static methods since you don't need an instance. Instance methods are those methods that require you to have an instance of a class.
Employee e = new Employee();
e.Terminate();
A static method is one that applies to the class a whole, not any particular member. .goExtinct() would be a method of the Duck population as a whole, not any particular duck. main is public and static because is has to always be available, and its not part of any particular class.
Usually, you have to have an object, an instance of a class, in order to call methods on it, for at least two reasons:
It depends on the object which class implements the method that is being called. For example if you have an instance of a subclass, the method in the subclass will be called instead, even though the code that calls the method is the same.
Objects usually have internal state (fields), that methods can refer to. This does not work if there is no object instance.
You create object instances by calling the class' constructor:
MyObject a = new MyObject();
Static methods are methods that are not attached to object instances. They can be called by just naming the class. As a result of this they
cannot be dynamically dispatched to subclasses (which is why you get a warning when you try to call it on object instances, that is just confusing syntax)
they cannot refer to instance state (non-static fields and other non-static methods).
Many people consider static methods a bad design pattern, and advise to not use them (except for public static void main) Look up the singleton instance pattern for an alternative.
In this particular case the main method must be static, because of the way the JVM will start loading classes and creating objects. When you start a Java program the JVM will look for the definition of the class that was passed to it and load it. So java MyClass will result in loading the definition of the MyClass class.
By definition a Java program will start executing in the main() method of the class that was passed to the JVM as the class to load initially. At this point in time no instance (object) of type MyClass has been created, so the main method has to be static to allow the start of the execution of your program.
If you want to see which classes are being loaded during the execution of a Java program you can use the -verbose:class command line option.
In any object oriented programming language like Java or C++ you create classes which at the very basic level are like BluePrints of a building. You can look at a blueprint and determine how various components are connected but you cannot actually live in it. It's the same with classes and object. Classes are blueprint and you create an instance of a class which is called an Object. For the same blueprint you can have multiple buildings , same way for one class you can have multiple objects. An Object is an instance of a class. Each method in a class can be called on an Object or an instance of a class, whereas for calling static methods you actually don't need an instance, you can directly call ClassName.method() without actually creating an instance of a class.
There will be times when you will want to define a class member that will be used independently of any object of that class. Normally a class member must be accessed only in conjunction with an object of its class. However, it is possible to create a member that can be used by itself, without reference to a specific instance. To create such a member, precede its declaration with the keyword static. When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object. You can declare both methods and variables to be static. The most common example of a static member is main( ). main( ) is declared as static
because it must be called before any objects exist.
The two types of static members are static fields and static methods:
Static field:
A field that’s declared with the static keyword, like this:
private static int ballCount:
The position of the static keyword is interchangeable with the positions of the visibility keywords (private and public, as well as protected). As a result, the following statement works, too:
static private int ballCount;
As a convention, most programmers tend to put the visibility keyword first.
The value of a static field is the same across all instances of the class. In other words, if a class has a static field named CompanyName, all objects created from the class will have the same value for CompanyName.
Static fields are created and initialized when the class is first loaded. That happens when a static member of the class is referred to or when an instance of the class is created, whichever comes first.
Static method:
A method declared with the static keyword. Like static fields, static methods are associated with the class itself, not with any particular object created from the class. As a result, you don’t have to create an object from a class before you can use static methods defined by the class.
The best-known static method is main, which is called by the Java runtime to start an application. The main method must be static, which means that applications run in a static context by default.
One of the basic rules of working with static methods is that you can’t access a nonstatic method or field from a static method because the static method doesn’t have an instance of the class to use to reference instance methods or fields.