Calling Constructor Multiple times - java

How to call the Constructor multiple times using the same object
class a
{
a(int i)
{
System.out.println(i);
}
public static void main(String args[])
{
a b = new a();
int x = 10;
while( x > 0)
{
//Needed to pass the x value to constructor muliple times
}
}
}
I needed to pass the parameter to that constructor.

Constructor of a class A constructs the objects of class A.
Construction of an object happens only once, and after that you can modify the state of the object using methods (functions).
Also notice if programmer does not write any constructor in his class then the Java compiler puts the constructor for the class (public constructor without any parameters) on its own.
In the case where a constructor has been provided by the programmer, the compiler does not create a default constructor. It assumes, the programmer knows and wants creation of the objects of his/her class as per the signature of the explicit constructor.
Constructor calls are chained. Suppose there exists below class relationship.
Child.java extends Parent.java and Parent.java extends GrandParent.java.
Now if Child child = new Child(); is done, only one object is created and that is of Child.java, but the object also has all of the features of GrandParent first then with the features of the Parent and then the Child.
Hence first constructor of GrandParent.java is called then Parent.java is called and lastly the constructor of Child.java is called.
Constructors are special and different from other methods.
The intent of constructors is to create the object, so each time you use the new operator, the constructor is called and a new object is created. You can not call the constructor directly. You need the new operator to call it. Even if you see some class defining methods like getInstance(), it still uses the new operator to construct the object and return the created object.
*PS there are ways to create an object without calling constructor (like Serialization) but that is out of context of the discussion here.

Constructors are called only once at the time of the creation of the object.
Can you please be specific about what you want to achieve?
But I think you could try one of the following two things.
Calling the constructor to create a new object and assigning it to the object 'b':
b = new a(1);
Using the setter method:
void setI(int i){
this.i = i;
}
b.setI(1);

int x = 10;
while( x > 0)
{
a b = new a(x);
}

Related

How is a child object constructed in Java?

In java, how is a child object constructed?
I just started inheritance and these few points are not very clear to me:
Does the child object depend only on the child class' constructor, or does it also depend on the parent's constructor? I need some details about that point.
Also, is super() always called by default in a child constructor?
Any other information regarding this topic is appreciated.
I don't think "A child object" is a good way to think about this.
You're making an object. Like all objects, it is an instance of some specific class, (After all, new SomeInterface() does not compile) and like (almost) all objects, it is made because some code someplace (doesn't have to be your code, of course) ran the java expression new SomeSpecificClass(args); somewhere.
We could say it is a 'child object' because SomeSpecificClass is a child class of some other class.
But that's rather useless. That means the only way to ever make a new 'non-child' object would be to write new Object(); - after all, all classes except java.lang.Object are a child class: If you write public class Foo {}, java will interpret that exactly the same as if you had written public class Foo extends java.lang.Object {}, after all.
So, barring useless* irrelevancies, all objects are child objects, and therefore as a term, 'child object', I'd not use that.
That also means that ALL object creation goes through this 'okay and in what order and how do the constructors work' song and dance routine.
How it works is probably most easily explained by desugaring it all. Javac (the compiler) injects things if you choose to omit them, because a lot of things that feel optional (such as a constructor, a super call, or an extend clause), at the class file / JVM level, aren't**.
Sugar #1 - extends clause
Already covered: if you have no extends clause on your class def, javac injects extends java.lang.Object for you.
Sugar #2 - no super call in constructor
A constructor must either call some specific super constructor on its very first line, or, it it must call some other constructor from the same class on its very first line (this(arg1, arg2);). If you don't, java will inject it for you:
public MyClass(String arg) { this.arg = arg; }
// is treated as:
public MyClass(String arg) {
super();
this.arg = arg;
}
Notably including a compiler error if your parent class has no zero-arg constructor available.
Sugar #3: No constructor
If you write a class that has no constructor, then java makes one for you:
public YourClass() {}
It will be public, it will have no args, and it will have no code on it. However, as per sugar #2 rule, this then gets expanded even further, to:
public YourClass() {super();}
Field inits and code blocks get rewritten to a single block.
The constructor isn't the only thing that runs when you make new objects. Imagine this code:
public class Example {
private final long now = System.currentTimeMillis();
}
This code works; you can compile it. You can make new instances of Example, and the now field will hold the time as it was when you invoked new Example(). So how does that work? That feels a lot like constructor code, no?
Well, this is how it works: Go through the source file top to bottom and find every non-static initializing code you can find:
public class Example {
int x = foo(); // all non-constant initial values count
{
x = 10;
// this bizarre constructor is legal java, and also
// counts as an initializer.
}
}
and then move all that over to the one and only initializer that classes get, in the order you saw them.
Ordering
So, via sugar rules we have reduced ALL classes to adhere to the following rules:
ALL classes have a parent class.
ALL classes have at least 1 constructor.
ALL constructors invoke either another constructor or a constructor from parent.
There is one 'initializer' code block.
Now the only question is, in what order are things executed?
The answer is crazy. Hold on to your hats.
This is the order:
First, set all fields to 0/false/null of the entire 'construct' (the construct involves every field from Child all the way down to Object, of course).
Start with the actual constructor invoked on Child. Run it directly, which means, start with the first line, which neccessarily is either a this() or a super() invocation.
Evaluate the entire line, notably, evaluate all expressions passed as arguments. Even if those are themselves invocations of other methods. But, javac will do some minor effort to try to prevent you from accessing your fields (because those are all uninitialized! I haven't mentioned initializers yet!!).
Yeah, really. This means this:
public class Example {
private final long x = System.currentTimeMillis();
public Example() {
super(x); // x will be .... 0
// how's that for 'final'?
}
}
This will either end up invoking the first line of some other constructor of yours (which is itself also either a this() or a super() call). Either we never get out of this forest and a stack overflow error aborts our attempt to create this object (because we have a loop of constructors that endlessly invoke each other), or, at some point, we run into a super() call, which means we now go to our parent class and repeat this entire song and dance routine once more.
We keep going, all the way to java.lang.Object, which by way of hardcoding, has no this() or super() call at all and is the only one that does.
Then, we stop first. Now the job is to run the rest of the code in the constructor of j.l.Object, but first, we run Object's initializer.
Then, object's constructor runs all the rest of the code in it.
Then, Parent's initializer is run. And then the rest of the parent constructor that was used. and if parent has been shifting sideways (this() invokes in its constructors), those are all run in reverse order as normal in method invocations.
We finally end up at Child; its initializer runs, then the constructor(s) run in order, and finally we're done.
Show me!
class Parent {
/* some utility methods so we can run this stuff */
static int print(String in) {
System.out.println("#" + in);
return 0;
// we use this to observe the flow.
// as this is a static method it has no bearing on constructor calls.
}
public static void main(String[] args) {
new Child(1, 2);
}
/* actual relevant code follows */
Parent(int arg) {
print("Parent-ctr");
print("the result of getNow: " + getNow());
}
int y = print("Parent-init");
long getNow() { return 10; }
}
class Child extends Parent {
Child(int a, int b) {
this(print("Child-ctr1-firstline"));
print("Child-ctr1-secondline");
}
int x = print("Child-init");
Child(int a) {
super(print("Child-ctr2-firstline"));
print("Child-ctr2-secondline");
}
final long now = System.currentTimeMillis();
#Override long getNow() { return now; }
}
and now for the great puzzler. Apply the above rules and try to figure out what this will print.
#Child-ctr1-firstline
#Child-ctr2-firstline
#Parent-init
#Parent-ctr
#the result of getNow: 0
#Child-init
#Child-ctr2-secondline
#Child-ctr1-secondline
Constructor execution ordering is effectively: the first line goes first, and the rest goes last.
a final field was 0, even though it seems like it should never be 0.
You always end up running your parent's constructor.
--
*) You can use them for locks or sentinel pointer values. Let's say 'mostly useless'.
**) You can hack a class file so that it describes a class without a parent class (not even j.l.Object); that's how java.lang.Object's class file works. But you can't make javac make this, you'd have to hack it together, and such a thing would be quite crazy and has no real useful purpose.
In inheritance, the construction of a child object depends on at least one parent constructor.
Calling the super () method is not mandatory. By default, Java will call the parent constructor without argument except if you precise a custom constructor.
Here an example
Mother
public class Mother {
int a;
public Mother() {
System.out.println("Mother without argument");
a = 1;
}
public Mother(int a) {
System.out.println("Mother with argument");
this.a = a;
}
}
child
public class Child extends Mother {
public Child() {
System.out.println("Child without argument");
}
public Child(int a) {
super(a);
System.out.println("Child with argument");
}
}
If you do this :
Child c1 = new Child();
you will get :
Mother without argument
Child without argument
If you do this :
Child c1 = new Child(a);
You will get :
Mother with argument
Child with argument
But if you change the second child constructor to and remove the super(arg) the parent constructor without argument will be called :
public Child(int a) {
// super(a);
System.out.println("Child with argument");
}
You will get :
Mother without argument
Child with argument
May be this course for beginners can help you Coursera java inheritance

Method overriding can have different number of parameters in subclass and parent class ?Can the no.of parameters differ?

We have parent class and child class having common method testparent() but there is difference in parameters
//Parent Class
public class Overriding {
int a,b,c;
//Parameters are different in number
public void testParent(int i, int j) {
System.out.println(a+b);
}
}
//Child Class Extending Parent Class Method
class ChildOverriding extends Overriding {
int c;
public void testParent(int i,int j,int k) {
System.out.println(a+b+c);
}
//Main Is not getting executed????
public static void main(String args[]) {
Overriding obj = new ChildOverriding();
obj.testParent(1,4,8);
}
}
}
Overriding Means sub class should have same signature of base class method.
Parameters and return type should be the same.
Actually your problem here is that you're accessing a method from SubClass over a reference object of a SuperClass.
Let me explain little bit more.
Super obj = new Sub();
This line will create one reference variable (of class Super) named obj and store it in stack memory and instance of new Sub() with all implementation details will be stored in heap memory area. So after that memory address of instance stored in heap is linked to reference variable stored in stack memory.
obj.someMethod()
Now when we call any method (like someMethod) on reference variable obj it will search for method signature in Super class but when it calls implementation of someMethod it will call it from instance stored in heap memory area.
That's the reason behind not allowing mapping from Super to Sub class (like Sub obj = new Super();) becuase Sub class may have more specific method signature that can be called but instance stored in heap area may not have implementation of that called method.
So your program is giving error just because it isn't able to find method signature that you're calling in super class.
Just remember Java will always look for method signature in type of reference object only.
Answer to your question is Yes, we can have different number of parameters in subclass's method but then it won't titled as method overloading/overriding. because overloading means you're adding new behaviour and overriding means changing the behaviour.
Sorry for my bad English, and if I'm wrong somewhere please let me know as I'm learning Java.
Thanks. :)
You can have the two methods, but then the one in ChildOverriding are not overriding the one in Overriding. They are two independent methods.
To fix your compilation problem, you have to either declare obj ChildOverriding
ChildOverriding obj = new ChilOverriding();
or you have to also implement a three-argument method in Overriding

Instance initialization block and subclasses

I'm getting confused about when the instance initialization block should run.
According to Kathy Sierra's book:
Instance init blocks run every time a class instance is created
So, consider having two classes: a parent and a child, according to this question and java's documentation:
instantiating a subclass object creates only 1 object of the subclass
type, but invokes the constructors of all of its superclasses.
According to the above:
why does the instance initialization block located in superclasses gets called every time an object of the subclass is instantiated? it isn't like that a new object of the superclass is instantiated.
After compilation instance init blocks become part of constructors. javac simply adds the init block to each constructor, that is this:
public class Test1 {
int x;
int y;
{
x = 1;
}
Test1() {
y = 1;
}
}
Is equivalent to this:
public class Test1 {
int x;
int y;
Test1() {
x = 1;
y = 1;
}
}
So the init block runs when constructor runs.
it isn't like that a new object of the superclass is instantiated.
Actually, it is like that.
Every instance of a subclass implicitly contains an instance of its superclass.
A superclass constructor is always invoked as the first step in any constructor (and that in turn runs any instance initializer blocks for the superclass)
Though it was a old post I came across this concept thought worth sharing it
Since we are talking about instance block here is how instance code flow executes in parent child relation class
// Child extends Parent
If we create a object for Child
1) Identification of instance members of the class from parent to child
2) execution of instance variable assignments and instance blocks only on parent class
3)execution of parent constructor
4)execution of instance variable assignments and instance blocks only on Child class
5)Execution of child constructor
Because there is always an implicit super() call(if not done explicitly) to the parent's constructor in the constructor of the child.

Get object's class and its constructor, Reflection in Android

suppose i have classA and classB(generic), reference http://www.exampledepot.com/egs/java.lang.reflect/Constructors.html
I am passing a customobject from classA to classB, now i am wanting constructor of customobject in classB and call it
classA
customclass objCustomclass;
classB mClassB;
mClassB.getConstructorAndCall(objCustomclass);
classB
public void getConstructorAndCall(Object objCustomclass);
try {
Object filledObject = objCustomclass.getClass().newInstance();
// here i need to call filledObject's contructor
} catch (Exception e) { }
I am able to create object as the instance of custom object but what about constructor.
note: getConstructorAndCall() is a commom method and in that object is of unknown type that means any class can pass its object.
Thanks.
well if the constructor is empty, then I think that what you have should run the constructor. Anything more complicated, like, passing parameters to the function can be done through:
Constructor[] constructors = objCustomClass.getClass().getConstructors()
for (int i = 0; i < constructors.length; i++) {
Constructor c = constructors[i];
Class[] paramTypes = c.getParameterTypes();
Object[] params;
// do fancy stuff here - it helps if you know what the constructors take beforehand
Object filledObject = c.newInstance(params);
}
Constructor with parameters
From the JavaDoc for java.lang.Class ( http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Class.html#newInstance() ):
Creates a new instance of the class represented by this Class object.
The class is instantiated as if by a new expression with an empty
argument list. The class is initialized if it has not already been
initialized.
I. E. the newInstance() method always uses the default constructor.
Most times I see people using new instance and requiring a particular constructor or signature, it happens to be due to a lack on the solution design. You might want to double check if a pattern applies to the solution you need.

Why isn't this method chosen based on the runtime-type of its object?

Consider this:
class A {
int x =5;
}
class B extends A{
int x =6;
}
public class CovariantTest {
public A getObject() {
return new A();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
CovariantTest c1 = new SubCovariantTest();
System.out.println(c1.getObject().x);
}
}
class SubCovariantTest extends CovariantTest {
public B getObject(){
return new B();
}
}
As far as I know, the JVM chooses a method based on the true type of its object. Here the true type is SubCovariantTest, which has defined an overriding method getObject.
The program prints 5, instead of 6. Why?
The method is indeed chosen by the runtime type of the object. What is not chosen by the runtime type is the integer field x. Two copies of x exist for the B object, one for A.x and one for B.x. You are statically choosing the field from A class, as the compile-time type of the object returned by getObject is A. This fact can be verified by adding a method to A and B:
class A {
public String print() {
return "A";
}
}
class B extends A {
public String print() {
return "B";
}
}
and changing the test expression to:
System.out.println(c1.getObject().print());
Unless I'm mistaken, methods are virtual in java by default, so you're overriding the method properly. Fields however (like 'x') are not virtual and can't be overriden. When you declare "int x" in B, you are actually creating a totally new variable.
Polymorphism doesn't go into effect for fields, so when you try and retrieve x on an object casted to type A, you will get 5, if the object is casted to type B, you will get 6.
When fields in super and subclasses have the same names it is referred to as "hiding". Besides the problems mentioned in the question and answer there are other aspects which may give rise to subtle problems:
From http://java.sun.com/docs/books/tutorial/java/IandI/hidevariables.html
Within a class, a field that has the
same name as a field in the superclass
hides the superclass's field, even if
their types are different. Within the
subclass, the field in the superclass
cannot be referenced by its simple
name. Instead, the field must be
accessed through super, which is
covered in the next section. Generally
speaking, we don't recommend hiding
fields as it makes code difficult to
read.
Some compilers will warn against hiding variables

Categories