What is the reason for initialization using constructor instead of method.
Code 1:
class A {
int x, y;
public A() {
x = 10;
y = 4;
}
}
Code 2:
class A {
int x, y;
public fun() {
x = 10;
y = 4;
}
}
From above, what is the difference between Code 1 and Code 2.
If any one know the answer please clear my doubt.?
It is guaranteed that constructor will get called when object is created but in case of method it is your control when to call. If you initialize values in method instead of constructor, there may be side effect if you call the method at wrong time.
Therefore it is always good practice to initialize the values in constructor instead of methods and that is the purpose of constructor.
First assignment occurs when instance is created. Second assignment occurs when you will execute the fun() method.
BTW you can call fun() method in constructor.
A constructor ensures that the object is properly instantiated. There's not guarantee that the caller will call the method to manually instantiate the object.
the constructor is called to create the instance of your class and does not rely on calls, unlike the method
When using code 1, A a = new A(); will init x and y.
When using code 2, you need A a = new A(); and a.fun(); to init x and y.
Init of your variables should be placed within a method if you wanna use this method also for additional inits sometime later.
btw fun is not an adequate name for a method.
A constructor is implicitly called when an object is created. In second case, the method is an instance level method.. You will have to create an object of type A and then "change" the values of x and y... The defualt constructor will assign default value (0) to your int variables...
Constructor used as initializer , because of it provide the functionality to initializing the object to memory or when a object is created at that time constructor will call first. If you don't initialize any value separately and you want to use some variable in your result then you can use constructor as initializer.
Why constructor use in coding? Bcz it have the nature to initialize some thing before of creation of Object.
I think you got my point. happy learning. :)
Thanks
Technically, you can hide constructor and use factory method pattern:
class A {
int x, y;
// Hidden constructor
protected A() {
x = 10;
y = 4;
}
// Factory method to create A class instances
public static A Create() {
...
A result = new A();
...
return result;
}
}
In your example factory method is an overshoot, but it could be helpful
when implementing singleton, strategy patterns etc.
Related
Consider the int a variables in these classes:
class Foo {
public int a = 3;
public void addFive() { a += 5; System.out.print("f "); }
}
class Bar extends Foo {
public int a = 8;
public void addFive() { this.a += 5; System.out.print("b " ); }
}
public class test {
public static void main(String [] args){
Foo f = new Bar();
f.addFive();
System.out.println(f.a);
}
}
I understand that the method addFive() have been overridden in the child class, and in class test when the base class reference referring to child class is used to call the overridden method, the child class version of addFive is called.
But what about the public instance variable a? What happens when both base class and derived class have the same variable?
The output of the above program is
b 3
How does this happen?
There are actually two distinct public instance variables called a.
A Foo object has a Foo.a variable.
A Bar object has both Foo.a and Bar.a variables.
When you run this:
Foo f = new Bar();
f.addFive();
System.out.println(f.a);
the addFive method is updating the Bar.a variable, and then reading the Foo.a variable. To read the Bar.a variable, you would need to do this:
System.out.println(((Bar) f).a);
The technical term for what is happening here is "hiding". Refer to the JLS section 8.3, and section 8.3.3.2 for an example.
Note that hiding also applies to static methods with the same signature.
However instance methods with the same signature are "overridden" not "hidden", and you cannot access the version of a method that is overridden from the outside. (Within the class that overrides a method, the overridden method can be called using super. However, that's the only situation where this is allowed. The reason that accessing overridden methods is generally forbidden is that it would break data abstraction.)
The recommended way to avoid the confusion of (accidental) hiding is to declare your instance variables as private and access them via getter and setter methods. There are lots of other good reasons for using getters and setters too.
It should also be noted that: 1) Exposing public variables (like a) is generally a bad idea, because it leads to weak abstraction, unwanted coupling, and other problems. 2) Intentionally declaring a 2nd public a variable in the child class is a truly awful idea.
From JLS
8.3.3.2 Example: Hiding of Instance Variables This example is similar to
that in the previous section, but uses
instance variables rather than static
variables. The code:
class Point {
int x = 2;
}
class Test extends Point {
double x = 4.7;
void printBoth() {
System.out.println(x + " " + super.x);
}
public static void main(String[] args) {
Test sample = new Test();
sample.printBoth();
System.out.println(sample.x + " " +
((Point)sample).x);
}
}
produces the output:
4.7 2
4.7 2
because the declaration of x in class
Test hides the definition of x in
class Point, so class Test does not
inherit the field x from its
superclass Point. It must be noted,
however, that while the field x of
class Point is not inherited by class
Test, it is nevertheless implemented
by instances of class Test. In other
words, every instance of class Test
contains two fields, one of type int
and one of type double. Both fields
bear the name x, but within the
declaration of class Test, the simple
name x always refers to the field
declared within class Test. Code in
instance methods of class Test may
refer to the instance variable x of
class Point as super.x.
Code that uses a field access
expression to access field x will
access the field named x in the class
indicated by the type of reference
expression. Thus, the expression
sample.x accesses a double value, the
instance variable declared in class
Test, because the type of the variable
sample is Test, but the expression
((Point)sample).x accesses an int
value, the instance variable declared
in class Point, because of the cast to
type Point.
In inheritance, a Base class object can refer to an instance of Derived class.
So this is how Foo f = new Bar(); works okay.
Now when f.addFive(); statement gets invoked it actually calls the 'addFive() method of the Derived class instance using the reference variable of the Base class. So ultimately the method of 'Bar' class gets invoked. But as you see the addFive() method of 'Bar' class just prints 'b ' and not the value of 'a'.
The next statement i.e. System.out.println(f.a) is the one that actually prints the value of a which ultimately gets appended to the previous output and so you see the final output as 'b 3'. Here the value of a used is that of 'Foo' class.
Hope this trick execution & coding is clear and you understood how you got the output as 'b 3'.
Here F is of type Foo and f variable is holding Bar object but java runtime gets the f.a from the class Foo.This is because in Java variable names are resolved using the reference type and not the object which it is referring.
Consider the code below. Fields i and j are initialized before m and n. We know that the parent object is created before the child object, but in my program the compiler is allocating and initializing memory for the child class' member variables before the base class'. Why is that?
class X
{
private int m = 0;
private int n = 90;
public X() { }
}
class Y:X
{
private int i = 8;
private int j = 6;
public Y()
{ }
public static void Main(string []args)
{
Y y1 = new Y();
}
}
This is explained in Eric Lippert's blog:
[...] an initialized readonly field is always observed in its initialized state, and we cannot make that guarantee unless we run all the initializers first, and then all of the constructor bodies.
Not sure why readonly is mentioned here, but for example, this ensures that the following scenarios, albeit being stupid, work:
1.
class Base
{
public Base()
{
if (this is Derived) (this as Derived).Go();
}
}
class Derived : Base
{
X x = new X();
public void Go()
{
x.DoSomething(); // !
}
}
2.
class Base
{
public Base()
{
Go();
}
public virtual Go() {}
}
class Derived : Base
{
X x = new X();
public override void Go()
{
x.DoSomething(); // !
}
}
This order is explicitly stated in C# Language Specification (17.10.2):
[...] constructor implicitly performs the initializations specified by the variable-initializers of the instance fields declared in its class. This corresponds to a sequence of assignments that are executed immediately upon entry to the constructor and before the implicit invocation of the direct base class constructor.
This is one of those rare places where an understanding of procedural methodology makes object-oriented methodology easier to understand. Even though you're working OOP, the compiler still adheres to procedural logic - working start to finish.
A simple example is when the compiler hits private int n = 90. First it allocates space for an integer value, then an identifier to access it as an integer, then assigns it the value of 90. It can't assign the value until it both has the space to stick it AND knows how to access it, nor can it access non-existent space.
In this instance, your derived class Y is built atop the base class X, similar to how the variable n is built atop the "class" integer in the example above. This is triggered by the declaration class Y:X - the compiler can't even start building Y until it understands how to build X.
Child construction code must be allowed to call functions on the parent, which can't work unless the parent is already fully-constructed.
However, the objects share the same memory block. So all the memory is allocated in one go, then the classes are initialized working up the class hierarchy.
I have a class in C# that has two constructors
public class GObject {
public GObject(){
// The default constructor
}
public GObject(int xPos, int yPos){
// Second constructor
}
}
Is this valid to write a sub-class Block like this?
public class Block : GObject {
// Sub class methods go here, no special constructor
}
And instantiate Block with the 2nd constructor?
Block myBlock = new Block(10, 15);
Since you don't have a two parameter constructor defined on Block, you can't write your final line - it will not compile.
You can have a chained constructor on Block:
public Block(int xPos, int yPos) : base(xPos, yPos)
{}
In which, case:
Block myBlock = new Block(10, 15);
Will work just fine.
By default, if you do not write the constructor explicitly; compiler creates a default constructor with no parameters.
In your case, since Block does not have any constructors defined, only parameterless constructor is created. Thus, you can not create a Block object using two parameters.
Consider the following code:
The code
public class RecursiveConstructor
{
//When this constructor is called
public RecursiveConstructor():this(One(), Two())
{
Console.WriteLine("Constructor one. Basic.");
}
public RecursiveConstructor(int i, int j)
{
Console.WriteLine("Constructor two.");
Console.WriteLine("Total = " + (i+j));
}
public static int One()
{
return 1;
}
public static int Two()
{
return 2;
}
}
The calling method
public class RecursiveConstructorTest
{
public static void Main()
{
RecursiveConstructor recursiveConstructor = new RecursiveConstructor();
Console.ReadKey();
}
}
The Result
Constructor two.
Total = 3
Constructor one. Basic.
Why is the 2nd constructor run first?
I understand that in chained constructors we call the base class constructor first and then make our way back up the chain but when the constructor is held in the same class why do we still see this behaviour where the extra constructor is called first?
I would have thought that the most basic constructor contents would be executed first.
I think the compiler runs the safer scenario.
If you call another constructor here, there are chances that this other constructor is a prerequisite to your current constructor. This behaviour is consistent with the one exposed when calling base constructors, and is then to be expected.
When creating a new instance of a class, there is a chain of constructors that get called from the least specialized (the constructor of the object class) to the most specialized (the constructor of your current class).
The operator : allows you to explicitly add a constructor to this chain, so this order seems natural.
You gave the explanation yourself. It is almost the same way base constructors are called. Whenever calling a constructor in your signature, like
public RecursiveConstructor() : this(One(), Two())
or
public RecursiveConstructor() : base()
the constructor right after the : is called first.
It makes sense when you consider that there is always a hierarchical chain of constructor calls when initializing new objects. As you rightly say, the base classes constructor is called first.
The two forms of constructor initializer, : base(...), which is often implictly called, and : this(...) behave the same way.
So, in your case we have a chain:
Object()
then...
RecursiveConstructor(int i, int j)
then...
RecursiveConstructor()
It is calling constructor 1 first, but ctor1 is calling ctor2 before it hits the ctor1 code block, hence the output you see.
One way around this, but to retain the DRY behaviour would be to refactor the (int, int) overload:
//When this constructor is called
public RecursiveConstructor()
{
Console.WriteLine("Constructor one. Basic.");
Init(One(), Two());
}
public RecursiveConstructor(int i, int j)
{
Console.WriteLine("Ctor 2");
Init(i, j);
}
private void Init(int i, int j)
{
Console.WriteLine("Refactored");
Console.WriteLine("Total = " + (i+j));
}
Out of interest, chaining constructors this way is often referred to as 'delegating constructors'.
In Java, it is possible to place the call to the other constructor in the code block (e.g. see here), but it must be the first line in the block
I'll try to keep this simple.
class MyClass {
private int x = 3;
}
vs.
class MyClass {
private int x;
public MyClass() {
x = 3;
}
}
What's the difference between the two and how do these differences come into play?
Thanks in advance.
class MyClass {
private int x = 3;
}
is same as
class MyClass {
private int x;
MyClass() { // default constructor based on the class access modifier
x = 3;
}
}
These are both the same
But if x were a static variable, they would be different.
Nothing at all. Variable's are set when a constructor is called, you can see this by adding the line MyClass temp = new MyClass() and stepping into it with the debugger, the debugger will go to the line private int x = 3; first.
Initialization of fields are done before constructor is called. But for your example they are same
In your example you actually have instance variable, not the class variable.
Difference comes in the moment when you add new constructor MyClass(Object argument) and forget to set x directly and forget to call original no-arg constructor as well. Making it final, if applicable, will of course force you to remember to set value somewhere.
In the case of class variable things get much more interesting, just change x to static and add following main method to the MyClass and observe results.
public static void main(String ... args) {
MyClass y = null;
System.out.println(y.x);
System.out.println(MyClass.x);
new MyClass();
System.out.println(MyClass.x);
}
As others has mentioned they both are equivalent. The main difference is the readability, duplicity and maintainability of the code. If we expand the given example to have more than one constructor you'll start to notice differences. If the value of x is not to depend on the constructor I'd recommend to initialize the field variable else set the value in the constructors. This will somewhat increase the readability and maintainability of the code and remove duplicated code (in the case were several constructors are to initiate the variable with the same value).