How main method called without calling it by classname.mainmethod() [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 11 years ago.
This is very basic question, many of us didn't know this answer. In java, to call static methods we have to follow this classname.method();. But when comming to main(), its not been called by classname.main() even though it is static.

The best way to understand how "main()" is called by JVM is to see how "java" calls your main method. Here is the JNI example explaining the same.
mid = (*env)->GetStaticMethodID(env, cls, "main", "([Ljava/lang/String;)V");
...
(*env)->CallStaticVoidMethod(env, cls, mid, args);

Yes it is. The java "interpreter" takes the class name you're giving it, looks for a static main method taking a String array as argument and returning void, and calls this method. The java interpreter probably does this using native code, but that's not important.
If, inside a program, you want to call another class's main method, you can. main methods are not special in this regard. The only special thing they have is that they can be the entry point for the java interpreter.

The main method is invoked by the java interpreter itself when you run the class, without have to add the class names.
you can find more detail explaination # Why is the Java main method static?

You can call static methods in Java as though they were instance methods but this is considered bad practice.
public class Foo {
public static void bar() { ... }
}
...
Foo foo = ...
foo.bar(); // this will work
Foo.bar(); // but this is better

It's being called with Class.main() as you have to provide the class containing a main() method, when starting an application.

But when comming to main(), its not been called by classname.main() even though it is static.
How can you say so? I am afraid you have got it wrong.
You can call a static method using object,though.
Usually you never call main yourself.It is an entry-point for your program and JVM calls it to start the execution of the program.
Also this is the reason you need to pass the name of the class when you execute your code.
Remember this:
java ClassName
This is how you execute your program from command line. ClassName here is the name of your Class having the main method.
This class name is used by JVM to call your main method e.g, ClassName.main()And all this calling stuff is done using native code C/C++.You might want to google it, in case you want to know exactly how all this works.If this is not exactly what you were looking for, maybe you can explain the question little more.
Hope this helps.

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.

When we can have class and method as static? [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.
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.

Thread object run method [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.
I need to write a program that uses multiple threads. I need to use the run() method after creating my thread objects. This run method seems to be built in. However, I need to write it and I need it to run a loop every time it is called. Can anyone help me understand how to do this?
You can create a new Thread instance by passing an anonymous implementation of the Runnable interface and then use the start() method to start the thread execution. See below:
Thread t = new Thread(new Runnable() {
public void run() {
while (!stopped) {
// do something interesting here
}
}
});
t.start();
Look at:
Counting Semaphores
http://tutorials.jenkov.com/java-concurrency/semaphores.html#counting
It's absolutely normal that the run() method is built into the Thread class. This class is meant to provide basic infrastructure for any class in your application that will represent a thread of execution. Think of Thread as 'any thread in the world'. Now the right way to use it in your application is to provide your own class that inherits Thread. This is done using extends keyword or using an anonymous class, like in Dan's answer. Let's assume you have extended the Thread class and called your class TaskToRunInParallel.
The documentation says that Thread class is special -- if you inherit it (like we just did) and put some code in the run() method of your own class (TaskToRunInParallel in our case), this code will be executed in parallel to the rest of the application. All you need to do is to call start() on the object of the class TaskToRunInParallel.
This is why the run() method is built-in: it provides you a prototype method to override in your own classes. This way any piece of code that works with Thread objects will be able to work with your TaskToRunInParallel objects, or any other class that inherits from Thread. Really: it is guaranteed that all of them will have run() method inherited from Thread and it's safe for that piece of code to call it. The result of this invocation will always be different though: each class inheriting from Thread may override run() in its own way. This is called polymorphism and together with inheritance is one of the cornerstones of object-oriented programming.
It's surprising how many concepts are involved when you think about overriding run() method of Thread class. Good luck.

Categories