The text book has it mentioned as:
System.out -> Class
Println -> Method
But, I disagree.
I think it's:
System -> Class
Out -> Method
Now, according to my logic, should Println be a method inside the method (Out)?
What is the correct concept here?
System.out isn't a class or a method, it's a static field on the System class that is a reference to an instance of a class (PrintStream). println is an instance method of PrintStream (or more completely, println is the common name shared by a group of instance methods that are overloaded with different arguments).
System is a class. Out is an object (public static final PrintStream out). println and print are methods. Trust the textbook.
Proof
Methods cannot contain other methods, plus "out" never has any parentheses or takes any arguments, so "out" cannot be a method.
Related
Is this statement true or false?
"The only way a constructor can be invoked is from within another constructor."
I thought a constructor could be invoked from within a method (and other places) if the call to the constructor is preceded with the keyword 'new'.
How about this statement? True or false?
"The only way a constructor can be invoked is from within another constructor (using a call to super() or this()), or from within static or instance methods, static or instance initializer blocks, or even constructors, if the call to the constructor is preceded by the keyword 'new'." Trying to invoke a constructor like you would invoke a method (using only its name) is not allowed."
Is this more accurate? "Where the call to the constructor is not preceded by the keyword 'new', the only way a constructor can be invoked is from within another constructor using this() or super() as the first statement."
Let's just go straight to the JLS, §8.8:
Constructors are invoked by class instance creation expressions (§15.9), by the conversions and concatenations caused by the string concatenation operator + (§15.18.1), and by explicit constructor invocations from other constructors (§8.8.7). [...]
Constructors are never invoked by method invocation expressions (§15.12).
Therefore, the first statement you quoted is technically false, as the JLS defines using new as invoking the constructor.
Note that your paragraph-length statement is a combination of true and false information; you can't invoke a constructor from static or instance methods except via creating a new object.
Rather than focusing on what the author of the original questions means by "invoke"1, here are the different ways that a constructor will be called.
By using the new operator with the class name and parameters that match the constructor signature:
Foon f = new Foon(1, 2);
It is also possible to do the same thing using reflection and the Constructor object equivalent to a new expression, or by using the relevant JNI or JNA callbacks in native code equivalent to a new expression. However, in all cases, the constructor invocation is conceptually happening at same point in the object creation. Hence I will treat them as identical.
By explicitly chaining to the constructor from another constructor in the same class using this(...).
By explicitly chaining to the constructor from a direct subclass constructor using super(...), or by implicitly chaining to a no-args constructor via an implied super() in a direct subclass constructor (declared or implied).
The implicit cases are merely "syntactic sugar" for the explicit super chaining cases.
There are a few other places where new is invoked behind the scenes by Java from regular Java code. A couple that spring to mind are string concatenation, auto-boxing, and the JVM throwing certain exceptions; e.g.
null.toString() // implicitly creates a NullPointerException obj.
1 - ... which is unknowable unless we understand the context, including how the OP's lecturer (or text book) is using the word "invoke".
It's true. You can't write code that actually calls a constructor as follows:
class Vehicle {
Vehicle() { } // Constructor
void doSomething() {
Vehicle(); // Illegal
}
}
The famous illusive constructor.
It's there when it's there, and even when it's not there it's still there.
The constructor is called at object creation.
So yeah the constructor can, or more precisely will be called if you create a object using new , na matter where you use it.
That quote of yours seems to be incomplete
"The only way the constructor of the superclass of the current class can be invoked is from within the current class constructor."
You can use the constructor when you use the class as an object in other class.
MyClass mc = new MyClass();
This statement is false.
'Invoking a constructor' can mean three different things:
You can invoke a constructor by creating a new object with the new operator:
String s = new String("abc");
In which case you will first allocate an object and then invoke the constructor:
NEW java/lang/String // allocate String instance
LDC "abc" // push the String constant on the stack
INVOKESPECIAL "java/lang/String"."<init>" : "(Ljava/lang/String;)V" // invoke constructor
The second way is to invoke another constructor from the same class:
class Super
{
Super(int i) { }
}
class Test extends Super {
Test() { this(1); }
// Bytecode:
INVOKESPECIAL "Test"."<init>" : "(I)V"
// ---------
The third way to invoke a constructor is to invoke one from the super class:
Test(int i) { super(i); }
// Bytecode:
INVOKESPECIAL "Super"."<init>" : "(I)V"
// ---------
}
Either way, the generated bytecode will contain an INVOKESPECIAL instruction. This means you are literally invoking the constructor in three cases, so if you define 'invoke' by that instruction, there is more than one way to invoke a constructor.
If you mean, directly invoking another constructor of the same object using the this(...) or super(...) construct (called explicit constructor invocation), the answer is yes.
It is probable that this is what the question meant but you have to be really precise in the wording and this question isn't.
Because if by "invoke" you mean, "causing a constructor to run", then you can "invoke" a constructor with the new keyword, which first allocates and creates the object, and then a constructor is run. In this, rather looser sense the answer is no.
But, importantly, new does a lot more than just calling the constructor. So in the most literal sense, calling new is not the same as invoking a constructor. Just like making tea involves pouring hot water but is not the same as simply pouring hot water.
Whether you want to make that distinction or not is up to you, or in this case the author of the question, you need to ask them.
I have following class:
class GroovyTest {
static class MyClass {
}
static main(def s) {
MyClass.print("hello")
}
}
It prints:
hello
Why would I need a print method that prints strings in every class?
Furthermore if I do:
MyClass.methods.each {println it}
It gives me a list of methods that MyClass has and print is not in the list.
Groovy adds many methods to classes at runtime. One of those methods is the print method which is added to java.lang.Object. See https://github.com/groovy/groovy-core/blob/194b29270d418b1b8642f5746a49873018f115c1/src/main/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L531. The way DefaultGroovyMethods works is such that the first argument to the method definition in that class represents the type that the method will be added to so something like this...
public static someMethod(SomeType o, SomeOtherType arg) {
// ...
}
That means that a method named someMethod will be added to SomeType and that method accepts an argument of type SomeOtherType.
I hope that helps.
Groovy adds a bunch of useful methods to the class Object, which means they are available to any object. Even classes, which are objects themselves. That is why you can do [].println().
This is strategy is used because Groovy, nor Java, have the concept of builtin functions like Python or PHP, which have print and echo, respectively. There are only objects and methods. There is no builtin println which you can simply call from nowhere. This is one of the ways to add a global-ish println function.
Seems like it is a builtin function in Ruby, also, as puts.
I really don't have an example, but I get confused between the two terms, as sometimes one is used and sometimes the other is used.
When a constructor is "invoked" is it also "executed"? Are they interchangeable?
Also, the word "call" is used a lot, as in "call a constructor".
And then there is "constructor completes".
I'm sure I'm not alone in my confusion, so an explanation with an example would be very helpful for many of us newbies trying to make sense of all of the terms.
I am using the Bates and Sierra book and here is the section that got me thinking about it:
"But what really happens when you say new Horse() ?
(Assume Horse extends Animal and Animal extends Object.)
1. Horse constructor is invoked. Every constructor invokes the constructor
of its superclass with an (implicit) call to super(), unless the constructor
invokes an overloaded constructor of the same class (more on that in a
minute).
2. Animal constructor is invoked (Animal is the superclass of Horse).
3. Object constructor is invoked (Object is the ultimate superclass of all
classes, so class Animal extends Object even though you don't actually
type "extends Object" into the Animal class declaration. It's implicit.) At
this point we're on the top of the stack.
4. Object instance variables are given their explicit values. By explicit values,
we mean values that are assigned at the time the variables are declared,
like "int x = 27", where "27" is the explicit value (as opposed to the
default value) of the instance variable.
5. Object constructor completes.
6. Animal instance variables are given their explicit values (if any).
7. Animal constructor completes."
The terms "invoke", "execute", and "call" mean the same thing and are interchangeable. What is meant by "constructor completes" is that the constructor finishes its invocation, or execution, or call, whatever your prefer.
Yes, they all mean the same thing. You might want to survey information on the topic from a few different sources whenever a textbook gets confusing. A very good place to look would be the official Java Tutorials, e.g. on constructors, which always has plenty of simple examples.
Technically, you "call"/"invoke" a method, it then gets "executed" and then "completes". And technically, if you have polymorphism there is an additional step "lookup which method should really be executed" between the "call"/"invoke" and "executed" steps.
"Invoke" is the same as "call" is the same as "execute", when talking about constructors or any other method.
A constructor is just another method, albeit a special one.
Best way to understand is by giving a sample of code:
class Animal {
public Animal(){}
}
class Horse extends Animal {
public Horse(){
super();//this line will be added by the compiler even if you didn't type it.
}
public Horse(String name){
this(); //this line will call the default constructor.
}
}
invoking the constructor is creating an instance from its class:
Horse horse = new Horse();
calling the constructor is done by:
super();//in our case it will call Animal constructor
or
this();//this will call the default constructor of the same class.
and you execute the constructor by calling or invoking it.
Iam pretty sure they are the same once the object is created or made the constructor is automatically called or invoked or indeed executed.
Let's look at the following code snippet in Java.
package trickyjava;
class A
{
public A(String s)
{
System.out.println(s);
}
}
final class B extends A
{
public B()
{
super(method()); // Calling the following method first.
}
private static String method()
{
return "method invoked";
}
}
final public class Main
{
public static void main(String[] args)
{
B b = new B();
}
}
By convention, the super() constructor in Java must be the first statement in the relevant constructor body. In the above code, we are calling the static method in the super() constructor parameter list itself super(method());.
It means that in the call to super in the constructor B(), a method is being
called BEFORE the call to super is made! This should be forbidden by the compiler but it works nice. This is somewhat equivalent to the following statements.
String s = method();
super(s);
However, it's illegal causing a compile-time error indicating that "call to super must be first statement in constructor". Why? and why it's equivalent super(method()); is valid and the compiler doesn't complain any more?
The key thing here is the static modifier. Static methods are tied to the class, instance methods (normal methods) are tied to an object (class instance). The constructor initializes an object from a class, therefore the class must already have been fully loaded. It is therefore no problem to call a static method as part of the constructor.
The sequence of events to load a class and create an object is like this:
load class
initialize static variables
create object
initialize object <-- with constructor
object is now ready for use
(simplified*)
By the time the object constructor is called, the static methods and variables are available.
Think of the class and its static members as a blueprint for the objects of that class. You can only create the objects when the blueprint is already there.
The constructor is also called the initializer. If you throw an exception from a constructor and print the stack trace, you'll notice it's called <init> in the stack frame. Instance methods can only be called after an object has been constructed. It is not possible to use an instance method as the parameter for the super(...) call in your constructor.
If you create multiple objects of the same class, steps 1 and 2 happen only once.
(*static initializers and instance initializers left out for clarity)
Yep, checking the JVM spec (though admittedly an old one):
In the instance init method, no reference to "this" (including the implicit reference of a return) may occur before a call to either another init method in the same class or an init method in the superclass has occurred.
This is really the only real restriction, so far as I can see.
The aim of requiring the super constructor to be invoked first is to ensure that the "super object" is fully initialized before it is used (It falls short of actually enforcing this because the super constructor can leak this, but that's another matter).
Calling a non-static method on this would allow the method to see uninitialized fields and is therefore forbidden. A static method can only see these fields if it is passed this as argument. Since accessing this and super is illegal in super constructor invocation expressions, and the call to super happens before the declaration of any variables that might point to this, allowing calls to static methods in super constructor invocation expressions is safe.
It is also useful, because it allows to compute the arguments to the super constructor in an arbitrarily complex manner. If calls to static methods weren't allowed, it would be impossible to use control flow statements in such a computation. Something as simple as:
class Sub extends Super {
Sub(Integer... ints) {
super(Arrays.asList(ints));
}
}
would be impossible.
This is one situation where the java syntax hides what's really going on, and C# makes it a bit clearer.
In C# your B would look like
class B : A {
public B() : base(method()) {
}
private static String method() {
return "method invoker";
}
}
Although the java syntax places super(method) within the constructor it's not really called there: All the parent initialization is run before your subclass constructor. The C# code shows this a little more clearly; by placing super(method()) at the first line of the java constructor you're simply telling java to use the parameterized constructor of the super class rather than the parameterless version; this way you can pass variables to the parent constructor and they'll be used in the initialization of the parent level fields before your child's constructor code runs.
The reason that super(method()) is valid (as the first line in a java constructor) is because method() is being loaded with the static elements--before the non-static ones, including the constructors--which allows it to be called not only before B(), but before A(String) as well. By saying
public B() {
String s = method();
super(s);
}
you're telling the java compiler to initialize the super object with the default constructor (because the call to super() isn't the first line) and you're ready to initialize the subclass, but the compiler then becomes confused when it sees that you're trying to initialize with super(String) after super() has already run.
A call to super is a must in java to allow the parent to get initalized before anything with child class starts.
In the case above, if java allows String s= method(); before the call to super, it opens up flood gate of things that can be done before a call to super. that would risk so many things, essentially that allows a half baked class to be used. Which is rightly not allowed. It would allow things like object state (some of which may belong to the parent) being modified before it was properly created.
In case of super(method()); call, we still adhere to the policy of completing parent initialization before child. and we can use a static member only, and static member of child classes are available before any child objects are created anyways. so the method is avilable and can be called.
OK..i think, this one could be relevant that, if we are calling some member with Super, then it first try to invoke in super class and if it doesn't find same one then it'll try to invoke the same in subclass.
PS: correct me if i'm wrong
Is this static println function in out class from System namespace?
namespace System {
class out {
static println ...
}
How can I interpret this name? And where in JRE this function is defined? In java.lang.System/java.lang.Object?
No. Actually out is a static member in the System class (not as in .NET), being an instance of PrintStream. And println is a normal (overloaded) method of the PrintStream class.
See http://download.oracle.com/javase/6/docs/api/java/lang/System.html#out.
Actually, if out/err/in were classes, they would be named with capital character (Out/Err/In) due to the naming convention (ignoring grammar).
System is a class, that has a public static field out. So it's more like
class System
{
public static PrintStream out;
}
class PrintStream
{
public void println ...
}
This is a slight oversimplification, as the PrintStream class is actually in the java.io package, but it's good enough to show the relationship of stuff.
System.out.println()
High level Understanding
For understanding this we need to recall few basics of java:
dot (.) operator in java: In java . (dot operator) is used only to call methods or variables.
So we can say out is either method or variable.
Methods in java : we know methods always have parenthesis ‘( )’ after method name, So out cannot be a method in java. So out its a variable and println() is a method.
Class name in java: Class name should start with Capital letter ideally in java, So System is a class.
Now with basic knowledge of java we know :
System is a Class
out is a Variable
println() is a method
Lets get more in details:
out variable: static or instance?
called using class name, so we know its static variable of System class.
but its calling a method println() method so ‘out’ is an object of the reference type PrintStream.
the System class belongs to java.lang package
class System {
public static final PrintStream out;
//...
}
the Prinstream class belongs to java.io package
class PrintStream{
public void println();
//...
}
Explained answer on my youtube what is System.out.println
Check following link:
http://download.oracle.com/javase/1.5.0/docs/api/java/lang/System.html
You will clearly see that:
System is a class in the java.lang package.
out is a static member of the System class, and is an instance of java.io.PrintStream.
println is a method of java.io.PrintStream. This method is overloaded to print message to output destination, which is typically a console or file.
println and print are the two overloaded methods which belong to the PrintStream class.
To access them we need an instance of this class.
A static property called out of type PrintStream is created on the System class.
Hence to access the above methods we use the following statements:
System.out.println("foo");
System.out.print("foo");
System.out.println("Hello World");
System: It is the name of standard class that contains objects
that encapsulates the standard I/O devices of your system.
It is contained in the package java.lang. Since java.lang package is imported in every java program by default,therefore java.lang package is the only package in Java API which does not require an import declaration.
out:The object out represents output stream(i.e Command
window)and is the static data member of the class
System.
So note here System.out (System -Class & out- static object i.e why its simply referred to by classname and we need not create any object).
println:The println() is method of out object that
takes the text string as an argument and displays it to the standard
output i.e on monitor screen.
Note
System -Class
out -static Object
println() -method
Remember a function (in java function is called method) always has the format function()
• System is a class in java.lang package
• out is a static object of PrintStream class in java.io package
• println() is a method in the PrintStream class
System is a class of java.lang package, out is an object of PrintStream class and also static data member of System class, print() and println() is an instance method of PrintStream class.
it is provide soft output on console.
It is quite simple to understand the question, but to answer it we need to dig deeper in to Java native code.
System is static class and cannot be instantiated
out is a reference variable defined in System
println() is the method used to print on standard output.
A brief and nice explanation is always welcome on this as we can learn much from this single line of statement itself!
Because out is being called with the System class name itself, not an instance of a class (an object), So out must be a static variable belonging to the class System. out must be instance of a class, because it is invoking the method println().
// the System class belongs to java.lang package
class System {
public static final PrintStream out;
}
class PrintStream {
public void println();
}
System is a class in java.lang package. And out is a PrintStream object. Nice explanation # http://lazy-geeks.blogspot.in/2015/01/what-is-systemoutprintln.html
System.out.println();
System is the class
out is a variable in the System class and it is a static and variable type is PrintStream.
Here is the out variable in System class:
public final static PrintStream out = null;
You can see implementation of System here.
println() is a overloaded method in PrintStream class.
PrintStream includes three overloaded printing methods, those are:
print()
println()
printf()
You can see implementation of PrintStream here.
You cannot instantiate System class and it is child class of Object and the Object is the father(superclass) of every classes including classes that you defined.
Here is what the oracle docs says:
public final class System extends Object
The System class contains several useful class fields and methods. It
cannot be instantiated.
Among the facilities provided by the System class are standard input,
standard output, and error output streams; access to externally
defined properties and environment variables; a means of loading files
and libraries; and a utility method for quickly copying a portion of
an array.
Since:
JDK1.0
If you donot know what is meant by instantiate, read this questioh. It is C# question but the concept is same.
Also, What is the difference between an Instance and an Object?
If you donot know what is meant by overload read this quesiotn.
System is a class in java.lang package.
out is the static data member in System class and reference variable of PrintStream class.
Println() is a normal (overloaded) method of PrintStream class.
From the javadoc about System, here's what the doc says:
public final class System
extends Object
The System class contains several useful class fields and methods. It cannot be instantiated.
Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.
Since:
JDK1.0
Regarding System.out
public static final PrintStream out
The "standard" output stream class Prinstream belongs to java.io package. This stream is already open and ready to accept output data.
When the JVM is initialized, the method initializeSystemClass() is called that does exactly what it’s name says – it initializes the System class and sets the out variable. The initializeSystemClass() method actually calls another method to set the out variable – this method is called setOut().
Typically this stream corresponds to display output or another output destination specified by the host environment or user.
Regarding println();
class PrintStream{
public void println();
}
For simple stand-alone Java applications, a typical way to write a line of output data is:
System.out.println(data);
System is the java class.
out is the instance and also static member of PrintStream.
println is the method of PrintStream.
System.out.println("...") in Java code is translated into JVM. Looking into the JVM gave me better understanding what is going on behind the hood.
From the book Programming form the Java Virtual Machine.
This code is copied from https://github.com/ymasory/programming-for-the-jvm/blob/master/examples/HelloWorld.j.
This is the JVM source code.
.class public HelloWorld
.super java/lang/Object
.method public static main([Ljava/lang/String;)V
.limit stack 2
.limit locals 1
getstatic java/lang/System/out Ljava/io/PrintStream;
ldc "Hello, world"
invokevirtual java/io/PrintStream/println
(Ljava/lang/String;)V
return
.end method
.end class
As "The JVM doesn't permit byte-level access to memory" the out object in type Ljava/io/PrintSteram; is stored in a stack with getstatic JVM command.
Then the argument is pushed on the stack before called a method println of the java/io/PrintStream class from an instance named out. The method's parameter is (Ljava/lang/String;) and output type is void (V).
System: is predefined class of java.lang package.
out: is a static member of printStream class and its connect with console.
Println: is a method of printstream class and its not a static.
System.out.println
System is a class in the java.lang package.
out is a static data member of the System class and references a variable of the PrintStream class.
System - class which is final in nature. public final class System{}. Belongs to java.lang package
out - static reference variable of type PrintStream
println() - non static method in PrintStream class.
PrintStream belongs to java.io package.
To understand it better you can visit : How System.out.println() Works In Java