Hi friends.
Consider the code below from "Thinking in Java".I have two confusions in this code.
//: c04:Flower.java
// Calling constructors with "this."
public class Flower {
int petalCount = 0;
String s = new String("null");
Flower(int petals) {
petalCount = petals;
System.out.println(
"Constructor w/ int arg only, petalCount= "
+ petalCount);
}
Flower(String ss) {
System.out.println(
"Constructor w/ String arg only, s=" + ss);
s = ss;
}
Flower(String s, int petals) {
this(petals);
//! this(s); // Can't call two!
this.s = s; // Another use of "this"
System.out.println("String & int args");
}
Flower() {
this("hi", 47);
System.out.println(
"default constructor (no args)");
}
void print() {
//! this(11); // Not inside non-constructor!
System.out.println(
"petalCount = " + petalCount + " s = "+ s);
}
public static void main(String[] args) {
Flower x = new Flower();
x.print();
}
} ///:~
Hi friends,
Consider the code segment below from "Thinking in Java"
//: c04:SimpleConstructor.java
// Demonstration of a simple constructor.
class Rock {
Rock() { // This is the constructor
System.out.println("Creating Rock");
}
}
public class SimpleConstructor {
public static void main(String[] args) {
for(int i = 0; i < 10; i++)
new Rock(); // line A
}
}
In the above code i have some confusions...
1:Bruce Eckel says " new Rock(); " at line A "creats an object
and storage is allocated and the constructor is called"
However, in my opinion new always creats a "New Object", but
how memory will captured or allocate without an "instance variable.
I mean if there is no "instance variable" then how it
is possible for object to occupie space in mempry i.e
it will take "Zero Bytes" in memory if it has no variable.
This means that object is not created!
2: Another thing is that, at " line A " we have not get the "reference"
of the object created by "new" and what i have learned is that if our programme
lost the reference of the object then that object is available for GC.What about
the objects created in above code?.Does they are available for GC?
Regards,
Hassan.