We all know that we cannot call a non-static method from Java's static main method directly. I've written 2 ways to call non-static method from main (shown below).
What I wanted to ask is: Is there any significance difference between using code 1 and code 2 to overcome the limitation?
Code 1
public class Demo
{
public static void main(String[] args)
{
Demo demo = new Demo();
demo.printText();
}
public void printText()
{
System.out.println("Method successfully called.");
}
}
Code 2
public class Demo
{
public static void main(String[] args)
{
new Demo().printText();
}
public void printText()
{
System.out.println("Method successfully called.");
}
}
NOTE: In school, our professor told us "In Java, staticmethods of a class can be invoked through the name of the class in which they are defined, without having to instantiate an object of the class first."
But in code 2 no object was instantiated, yet I was able to call the non static-method?
There are 2 main things to be considered while using the first one over the second..
you will still have a reference to the Demo object, so you can call demo.someOtheMethod().
Your demo object will not be ready for Garbage collection as soon as printext() returns. i.e, it will not be ready until you actually exit main(). In the second case, it will be ready as soon as printext() returns..
The only difference is that you can reuse the value in the object demo later. However, you should not create an instance just to call such a method. The correct way to do this is to make the method static.
There is no any difference of executing code or the creating the object.
But in the second method, you don't have a reference to the object you created.(in first method, demo is the reference for the Demoobject) So you can't do any other thing with this object further, as there is no way of referencing it.
as example:
Suppose you had another method inside class Demo called foo1()
in first example you can run both method using a single object.
Demo demo = new Demo();
demo.printText();
demo.foo1();
but in the second method, You have to do it with 2 objects seperately.
new Demo().printText();
new Demo().foo1();
In Code1, you are creating an object using the class name as a reference variable, and calling that function and this would work very finely.
in code2, you are creating an anonymous object, which is basically used whenever we want to use the object only once in the lifecycle of the class.
In both code, the program will work finely.
Related
I think I am missing something. I want to call a method in an object from a statement in an object of a different class but if I do that the compiler tells me that it cannot find symbol.
public class Test1
{
public static void main (String[] args)
{
Second secondObj1 = new Second();
Third thirdObj1= new Third();
thirdObj1.accessMethodinSecondObj1();
}
}
class Second
{
int m1;
Second()
{
m1 = 0;
}
public void methodinSecond()
{
System.out.println(m1);
}
}
class Third
{
void accessMethodinSecondObj1()
{
secondObj1.methodinSecond();
}
}
So what I am trying to do is run method secondObj1.methodinSecond() from thirdObj1.accessMethodinSecondObj1(). Obviously, this example is a bit silly but it is related to a real problem - but I feel the full code would be too confusing.
I can solve the problem by passing the object reference for secondObj1 to thirdObj1 by changing the signature etc., but it seems very convoluted. Maybe there is a better way?
It seems to me that because I declared secondObj1 in the main method then the object itself is only visible within the main scope? Is there no way to allow objects of Second and Third to "talk" to each other directly, meaning call each other's methods?
secondObj1 is a local variable of the main method. A local variable is visible only in the block where it's declared. So it's visible only inside the main method. Not inside the method accessMethodinSecondObj1 of Third.
If you want this method to access the object referenced by `secondObj1, you need to pass that object as argument to the method:
In main:
thirdObj1.accessMethodinSecondObj1(secondObj1);
In Third:
void accessMethodinSecondObj1(Second s) {
s.methodinSecond();
}
Just like, to print the value of m1, you pass m1 as argument to the method println() of System.out.
The compiler message is about scope, yes.
But there is a more fundmental flaw in your code. What is you have another Second object and you want to call a method in that one? Your Third class objects expect any Second class object to be named 'secondObj1'.
You already indicated an solution, change te signature so that the object of class Second you want to access can be passed:
void accessMethodinSecondObj(Second secondObj)
{
secondObj.methodinSecond();
}
And then:
thirdObj1.accessMethodinSecondObj(secondObj1);
You're along the right lines. You are correct that the scope of secondObj1 is limited to the main method where it is created. So how do we pass secondObj1 to thirdObj1, as they're not globally available?
This first thing to note is that these objects have a relationship. Our class Third has a dependency upon Second. Third can't perform its responsibility in accessMethodinSecondObj1() without an instance of Second. In which case, we have a few options.
Thie simplest of which is to inject the dependency where it is needed. In this case, into the accessMethodinSecondObj1() method as such:
public class Third
{
public void accessMethodinSecondObj1(Second secondObj1)
{
secondObj1.methodinSecond();
}
}
To call this from main, simply:
public class Test1
{
public static void main (String[] args)
{
Second secondObj1 = new Second();
Third thirdObj1 = new Third();
thirdObj1.accessMethodinSecondObj1(secondObj1);
}
}
You could inherit from Second as to access its members and methods and call from within thirdObject1.accessMethodinSecondObj1() using super.methodinSecond(). But as we're dealing in abstractions here, it's a difficult solution to suggest as it may not make semantic sense in your domain.
In which case, another option is composition. We inject an instance of Second into Third via the constructor and that instance of Third then owns that instance of Second. By doing so, we ensure Third has an instance of Second (upon which it depends) when this method is called. This also enables the performing of validation operations on the passed instance of Second before we use it in accessMethodinSecondObj1().
public class Third
{
private Second secondObj1;
public Third(Second secondObj1)
{
this.secondObj1 = secondObj1;
}
public void accessMethodinSecondObj1()
{
this.secondObj1.methodinSecond();
}
}
In which case, within main we would do the following:
public class Test1
{
public static void main (String[] args)
{
Second secondObj1 = new Second();
Third thirdObj1 = new Third(secondObj1);
thirdObj1.accessMethodinSecondObj1();
}
}
As we can see
public void methodinSecond()
{
System.out.println(m1);
}
is not static and therefore in
secondObj1.methodinSecond();
you cannot call a method without creating an object if it is non-static
In your main method
Second secondObj = new Second();
the scope of the variable would be only inside the block so if you want to use it in the method of class Third pass it as a parameter to the method
thirdObj1.accessMethodinSecondObj1(secondObj);
and also change the method to
void accessMethodinSecondObj1(Second secondObj)
{
secondObj.methodinSecond();
}
When studying the java programming language, I meet the following statement
I am confusing about the statement marked with yellow. Especially, what does instance method mean here? If there is an example to explain this point, then it would be much appreciated.
If I have a method:
public static void print(String line) {
System.out.println(line);
}
... and then remove the static keyword ...
public void print(String line) {
System.out.println(line);
}
... it is now an instance method, can no longer be invoked from the class, and must instead be invoked from an instance (hence the name).
e.g.,
MyClass.print(line);
vs.
new MyClass().print(line);
That's really it.
You can call static methods without needing to intantiate an object:
TestObject.staticMethodCall();
For non-static methods you need to create an instance to call a method on:
new TestObject().nonStaticMethodCall();
Consider following sequence.
Define Class X with static void foo() a static method
Define Class Y which calls X.foo() in its main method
Compile the two classes and (somehow) run it
Change X.foo() to be a instance method by removing the static qualifier
Compile only X, not Y
Run the Y class again and observe the error.
On the other hand, if you had changed the body of X.foo in certain ways without changing its static-ness then there would have been no error. For more, look up "binary compatibility"
First of all, you should understand the difference between the class method and the instance method. An example is shown below.
public Class Example{
public static void main(String[] args) {
Example.method1();//or you can use method1() directly here
Example A = new Example();
A.method2();
}
public static void method1(){
}
public void method2(){
}
}
method1 is the class method which you can take it as the method of the class. You can invoke it without initiating a object by new method. So you can invoke it in such way: Example.method1()
method2 is the instance method which requires you to invoke it by initiating the instance of an object, i.e. Example A = new Example(); A.method2();
Additional:
The error is due to the removal of the static modifier of an class method like method1. Then method1 becomes an instance method like method2 which you have to initiate an instance to call.
Whenever we use static, we need not create a reference variable of a class. We can directly access class with the help of <class_name>
But when we write the following code:
class Abc
{
static void show()
{
System.out.println("Hey I am static");
}
}
class Test
{
public static void main(String args[])
{
Abc.show(); //1
new Abc().show(); //2
}
}
How does both the lines 1 & 2 work. what is the significance of
new Abc().show();
Using an instance (although it works) is the wrong way of invoking a static method (or access static fields) because static denotes its a member of the class/type and not the instance.
The compiler would therefore replace the instance with the Class type (due to static binding). In other words, at runtime, ABC.show() gets executed instead of new ABC().show().
However, your source code would still look confusing. Hence, it's considered a bad practice and would even result in warnings from IDEs like Eclipse.
Since your ABC class did'nt override the default constructor.
It's equivalent to :
class Abc{
public Abc(){super();}
static void show(){
System.out.println("Hey I am static");
}
}
Hence by doing new Abc().show(); you're just creating a new Abc object of your class and call the static method of the ABC class throught this object (it will show a warning because this is not the proper way to call static method).`
You CAN use static methods from an instance, as in new Abc().show(), but it's potentially confusing and not recommended.
Stick to className.staticMethod() for static methods and classInstance.instanceMethod() otherwise.
It simple means that you are creating object to ABC and than trying to accessing this variable through object.
However, at the time of compilation,
new Abc().show();
is converted to Abc.show().
Static keyword suggests only one copy per class now you have created method static and you are accessing using Classname.methodname() that is appropriate way because when class is loaded into JVM its instance will be created so no need to exlicitly create new Object of the class. hope it make sense.
I have a simple Java theory question. If I write a class that contains a main() method along with some other methods, and within that main method invoke an instance of the class (say new Class()), I'm a bit confused why a recursion doesn't occur. Let's say I'm writing a graphing program, where the other methods in the class create a window and plot data; in the main method I call an instance of the class itself, and yet only one window appears. That's great, and it's what I wanted, but intuition suggests that if I create an instance of a class from within itself, some sort of recursion should occur. What prevents this? Here is an example (in my mind, I'm wondering what prevents unwanted recursion):
public class example{
method1(){create Jpane}
method2(){paint Jpane}
method 3(){do some computations}
public static void main(String[] args){
new example(); // or create Jblah(new example());
}
}
I think you're confusing the main method - which is just the entry point of the program - with a constructor.
For example, if you wrote:
public class Example {
public Example() {
new Example(); // Recursive call
}
public static void main(String[] args) {
// Will call the constructor, which will call itself... but main
// won't get called again.
new Example();
}
}
Then that would go bang.
The main method does not get executed automatically when you instance a class. It simply can be used as an entry point to an application - and then will be executed once.
Recursion isn't a bad thing. I suspect you are asking why there isn't an infinite recursion.
The big concept you are missing is that when you call new Example() you are allocating memory and then invoking just one method (the constructor). The main() is only invoked at the start of the whole program unless you explicitly call it.
--- edited to add
public class MyMainClass {
public static void main(String arg[]) {
Calculator c = new Calculator();
int x = c.factorial(5);
}
}
class Calculator {
Calculator() { }
public int factorial(int x) {
if (x > 1) return x * factorial(x - 1);
else return 1; // WARNING: wrong answer for negative input
}
}
Since factorial doesn't use any instance variable, it could have been declared static and called as Calculator.factoral(5); without even using new, but I din't do that since showing off new was the whole point of the example.
just because you have a main method in the class doesn' mean that it will be called every time you create the class.
Java looks for main as an entry point for the program, and calls it upon startup. Any objects you instantiate from their do not call main, since as far as java is concerned, it has done its job of making the entry point to the program.
Suppose the classes has code like this:
class C {
public static void show() {
}
}
class CTest {
public static void main (String[] args) {
C.show();
}
}
Then will it be perfectly legal to conclude that while referring to class C to access the static method show() here, behind the scene Java is actually calling the show() method through Java reflection ?
I.e. is it actually doing something like this
Class test = Class.forName(C);
test.show();
to call static methods?
If not, then how is it actually calling the static methods without creating objects?
If the above explanation is true, then how we'll justify the statement that "static members are only associated with classes, not objects" when we're actually invoking the method through a java.lang.Class object?
The JVM doesn't need to do anything like Class.forName() when calling a static method, because when the class that is calling the method is initialized (or when the method runs the first time, depending on where the static method call is), those other classes are looked up and a reference to the static method code is installed into the pool of data associated with that calling class. But at some point during that initialization, yes, the equivalent of Class.forName() is performed to find the other class.
This is a specious semantic argument. You could just as easily say that this reinforces the standard line that a static method is associated with the class rather than any instance of the class.
The JVM divides the memory it can use into different parts: one part where classes are stored, and one for the objects. (I think there might have been third part, but I am not quite sure about that right now).
Anyways, when an object is created, java looks up the corresponding class (like a blueprint) and creates a copy of it -> voila, we have an object. When a static method is called, the method of the class in the first part of the memory is executed, and not that of an object in the second part. (so there is no need to instantiate an object).
Besides, reflection needs a lot of resources, so using it to call static methods would considerably impact performance.
For extra info:
The called class will get loaded when it's first referenced by calling code.
i.e. The JVM only resolves and loads the class at the specific line of code that it first needs it.
You can verify this by using the JVM arg "-verbose:class" and stepping through with a debugger.
It will call ClassLoader.loadClass(String name) to load the class.
You can put a println statement into the ctor, to verify, whether it is called or not:
class C {
public static void show () {
System.out.println ("static: C.show ();");
}
public C () {
System.out.println ("C.ctor ();");
}
public void view () {
System.out.println ("c.view ();");
}
}
public class CTest
{
public static void main (String args[])
{
System.out.println ("static: ");
C.show ();
System.out.println ("object: ");
C c = new C ();
c.view ();
c.show (); // bad style, should be avoided
}
}