If 'Main' Is an Instance of 'Object', Why Can't I Call It

Java: Why can't I call this method outside of main?

In Java, you can't have executable statements that aren't part of a method.* The first line is okay:

VelocityCounter caller = new VelocityCounter();

because the compiler thinks you are declaring and initializing an instance variable named caller for class Velocity2. The second line, however:

caller.VelocityC(6, 3);

is illegal at the top level of a class declaration.

*Technically, that's not quite right. Statements can also appear in constructors, static blocks, and instance initializer blocks.

new instance of the class in java main method

In java a class has fields and methods (or functions). Keyword 'static' can be added to both of these entities.

Entities marked with keyword 'static' are class related and other entities are instance related. For accessing static fields or methods of a class we require only the class and its instance (created by using new keyword) is not required to be created.

Methods and fields which are not marked static belong to an active instance of the class.

Now suppose there is a class Test.java and we have no instance of it. We can call any of its method which is marked as static. Try thinking an answer to : "From inside an static method (without an instance of the class) how can we call a method or how can we access a field which belongs to some instance?"

For acessing non static field or method from an static method we need an instance. If the 'calling method' is non static then it must have been invoked on an object. If now we call another method from this non static 'calling method' we can eaisly do that as that method will be invoked on the same object as on which the 'calling method' has been invoked upon.

As mentioned by Xavi in his answer you can also refer to
https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html for understanding about 'static'.

All non static methods and fields have 'this' (https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html) associated with them, which refers to the current active instance of the class.

Hence 'main' method being static can not call any non static method without instance of the class 'Test'

Why do I need to create an instance of the class I am working in?

Why can I not call those methods and functions from the main without creating a new object of the class?

Because they are not static

You have to create an instance to be able to use them. Add the modifier, so you can have access to them. For instance,

private static getSomething()

And then, call it from main as:

getSomething()

Also pay attention to what the almighty @JonSkeet said in the comments.

Why can't we access static method through the object in .net

As for every question on a language-decision you allways have to consider the use and the potential harm that is caused by your request. While it may increase your (personal) readability in a very specific case, it adds lots of confusion to readers of your code that don´t have your source-code. Furthermore it would assume a compiler is able to determine if or if not a member actually does something on the instance or not. So the compiler would have far more complicated logic in order to achieve something you can easily indicate yourself by the static keyword.

In fact an instance-method does something with an instance, it does not neccessarily modifiy its state, it can also just use that state and process some operation. Making something available on that instance-level which does not have instance-semantics seems quite counter-intuituve and breaks the principle of least astonishment - at least for me. If there is a member called on an instance it is supposed to do something with that instance. If or if not this is actually the case is an implementation-detail which a client shouldn´t bother for at all.

why can't I create another method aside from main method in main class?

I guess you using a code like this.

public class TestClass {

public static void main(String[] args) {
doSth();
}

public void doSth() {

}

You cannot call a non-static method from the main class.
If you want to call a non-static method from your main class, instance your class like this:

TestClass test = new TestClass();
test.doSth();

and call the method.

Can't call method from another class in Java

You have to do something like below:

public class Persona {
...
//You should have instance of RegistroCompra
RegistroCompra registraCompra = new RegistroCompra();
public void setDestino() {
//Option 1: Explicitly call the method
registraCompra.seleccionarDestino();
destinoPasajero = registraCompra.obtenerDestino();
}
}

public class RegistroCompra {

private String destino;

public RegistroCompra(){
//Option 2 : Call the method in constructor
registraCompra();
}
public void seleccionarDestino() {
...
//Set the input to the class level variable destino
this.destino = input.nextLine();
}
public String obtenerDestino() {
return this.destino;
}

}

Java: How To Call Non Static Method From Main Method?

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.

Why can I access a private variable from main method?

Main is a part of you class, you have declared it inside your class :)
What main is not is part of your object, it will not be any part of the objects you create from the class but it is still part of the class. This is correct for any static function as main is just a normal static function that the framework knows it should look for when the program is executed.



Related Topics



Leave a reply



Submit