When exacty is the object initialized? - java

I want to ask you when is the exact moment when an object is initialized
For example I have this simple Java code:
public class Test {
public static void main(String args[]) {
Student student = new Student();
student.setName("John");
student.setId(123);
}
}
So when exactly is the student object initialized? Is it initialized when new Student() is executed? Or when Student student = new Student() is executed? Or after setters are executed? Any feedback will be appreciated!

It's initialized when new + constructor is called.
As states the docs
Each of these statements has three parts (discussed in detail below):
Declaration: The code set in bold are all variable declarations that
associate a variable name with an object type.
Instantiation: The
new keyword is a Java operator that creates the object.
Initialization: The new operator is followed by a call to a
constructor, which initializes the new object.

Is it initialized when new Student() is executed?
Yes. When the resulting object is returned, it has been initialized (by the constructor code).
Or after setters are executed?
The fields of the object are initialized by the time the constructor returns. They may be set to null or "" or 0 or similar, but they're initialized with some value.
If it's not valid for a Student object to have null or whatever for those fields, then the constructor should accept the values for them as parameters, or the class should expose a builder-style interface for building an instance, so that by the time you have a Student instance, you know the fields are filled in with meaningful values. Whether that's necessary is domain-specific.

It depends on your constructor class. Probably line three, but if your mutator methods create new objects then line 4 and 5.

It get initialized when new Student() is executed.
new Student() - this calls the constructor of the Student Class.
After that, the resulting object is assigned to the 'student' variable where the data type is Student.

Whenever 'new' keyword is invoked, the object is instantiated and the constructor is called resulting in object initialization.
First of all, see the difference between a setter and constructor and their pros and cons.
Constructor:
1) A constructor is called when an object is created.
2) They are only called once per object.
3) You may use the constructor to set values at the point of instantiation.
4) It does not allow any return type.
5) A constructor is invoked implicitly.
Setter:
1) A setter is called to change the value of the object after it was initialized.
2) A setter can be called any number of times.
3) You may use the setter to set values after the point of instantiation.
4) It allows return type.
5) A setter is invoked explicitly.
Conclusion:
1) Object is initialized when new Student() is executed
2) Use constructor if you think initialization is mandatory and you have the required values before you can use the object.
3) Use the setter method when the initialization of the variable is non-mandatory and you don't have the values at the time of object initialization.
4) Generally, we should avoid setter as it somehow violates the principle of encapsulation.

Student student = new Student();
When you call new and then the constructor you are creating an object of the same type of your constructor class, the object that is receiving the new + constructor must be the same type.
Another example:
Object that must be the same as your class + name of the object signal = then new plus constructor;
Example exaple = new Example();

When you call
Student student = new Student();
you are creating an object in memory. Once created, you can use the object's methods, like getters and setters.

Related

Don't understand the link between constructor and object

I'm trying to learn java and and moving along OK but I ran across this example and I don't understand how "tommy" is passed from myPuppy to name. Can someone explain how that works? I don't understand how the 2 are linked.
public class Puppy {
public Puppy(String name) {
// This constructor has one parameter, name.
System.out.println("Passed Name is :" + name );
}
public static void main(String [] args) {
// Following statement would create an object myPuppy
Puppy myPuppy = new Puppy( "tommy" );
}
}
If we compile and run the above program, then it would produce the following result:
Passed Name is :tommy
It's not passed from myPuppy to name. What happens is:
A new Puppy object is created when the new Puppy(...) expression is evaluated.
The constructor is called. Each parameter in the constructor (in this case, name) is replaced with the argument that is passed to new. In this case "tommy". So inside the constructor, the variable name now refers to the string tommy.
Then the new constructed object is assigned to the variable myPuppy.
You can think of the Constructor as a function having one parameter which is "name". In the body of this function, you have the console printing statement.
Once you call it in your main program, then a Puppy will be initialized with the name provided, which is "tommy" in here.
Once you have this object initialized, the name will be printed on the screen.
As the name already implies, a constructor constructs an object. An object is an instance on a class. In your case Puppy is the class you are creating an object of.
In Java a new object is created by the new keyword. You can think of the constructor being called like a function when you create a new object of a class.
In this case new Puppy("tommy") will pass the constructor a reference to the String "tommy" and will assign it to the variable name. The System.out.println(...) call will then be passed the reference to "tommy" and print it out on the console.

Why we do not create object for static method in java?

Sometimes we call className.methodName() without creating object for it, I mean without using syntax as className objectName = new constructor() and then call as object.methodName()
When to use className.methodName()?
When to call method using object as object.methodName()?
Explanation of above two cases with example will be appreciated.
What you're referring to is a static method.
Assume that I have this :
public class A {
public static void foo(){
System.out.println("Hooray! I work!");
}
}
You can now do this anywhere else in any other class :
A.foo();
This is because the method is static, which means that it can be called on by the CLASS.
This means that it doesn't require an instance of that class in order for the method to be called.
However, even though it isn't required, you can still do this :
A a = new A();
a.foo();
But since the method foo() is static, instantiating an object A is not required in order to run the foo() method.
First. When you're create at least one static method of a class, you can use this method without creating an instance of class. This is useful, for example, for the creation of methods with independent logic. For example:
public class Checker {
public static Boolean month(int value) {
return (value >= 1 && value <= 12);
}
}
You need check correct value of month many times. But what to do each time to create the object. It is much effective to use a static method.
Second. When you create the object, the object is stored in the memory and you get a link to it. Then the object can be used for example to save at the list.
Method at this object is specific. You can save class data and do specific operation with member of this class. For example:
List<Animals> animalsList = new ArrayList<>();
Animal animal = new Animal("dog");
int legs = animal.getCountLegs(); // specific function for object
animalList.add(animal); //save if you need
// use list of object
For every class, we have a Object called as class object which is YourClass.class object. static methods are invoked based on meta-data on those objects. For instances of a class, methods are invoked on the actual instances. Both static and non-static methods are present on method area.
There is no different between 1 and 2 point, because in during compilation compiler makes ClassName.staticMethod() instead of instance.staticMethod().
Static methods in java belong to the class (not an instance of it). They use no instance variables and will usually take input from the parameters, perform actions on it, then return some result. Instances methods are associated with objects and, as the name implies, can use instance variables.

object oriented programming, constructor with parameters

So here is the code, and there are few lines I don't understand.
account acct = new account(); // making a new object named acct, type:account
ConsoleAccountEvents c1 = new ConsoleAccountEvents(acct); // new object created with parameters.
acct.addObserver(c1); // also not sure.
acct.addTransaction(100.00); // not sure....
This is Java. I'm not sure how parameters are passed to the constructor.
In java, the constructor is invoked when the object of the class is created using the new keyword. So to call the constructor with a certain parameter you just have to create an object with parameter as per your requirement example in your case.
class ConsoleAccountEvents {
Account account;
public ConsoleAccountEvents(Account account) {
this.account = account;
}
}
class Account {
}
So when you create object with
Account acct = new Account();
ConsoleAccountEvents c1 = new ConsoleAccountEvents(acct);
So here parameterized constructor will be called and this object will be assigned in instance variable of ConsoleAccountEvents class
Your ConsoleAccountEvents class must look like something like this-
class ConsoleAccountEvents {
Account accObject; // you have an object of 'Account' class as a member variable in this class
// other variables
public ConsoleAccountEvents() {
// body here
}
public ConsoleAccountEvents(Account accObject) {
this.accObject = accObject; // see below
// body here
}
// others
}
Doing this ConsoleAccountEvents c1 = new ConsoleAccountEvents(acct);
You are calling the parametrized constructor which takes an Account object as parameter and generally initialize the accObject (object of Account class) in ConsoleAccountEvents with it.
Now, For acct.addObserver(c1);
In your Account class you must have a method addObserver that takes a ConsoleAccountEvents as parameter. like
void addObserver(ConsoleAccountEvents evOb) {
// body
}
PS: Please follow java naming conventions and other conventions, like capitalizing the first letter of name of a class etc.
And stackoverflow is not going to be of much help if you dont go through Java Language Tutorial. Good luck...!
I think what you may be looking for is how the new keyword works, but let me be thorough:
Some things to note about constructing objects in Java:
A constructor will be called every time you "request" a new Account().
A constructor can be defined to use parameters (and thus require arguments) of any type - both class types and primitive types (int, float, char, etc..)
If the constructor is called like new SomeClass(someObject), someObject is the argument passed to the constructor of SomeClass.
In the constructor of a class, parameters are defined with a type and a name as such:
class ConsoleAccountEvents{
Account account;
ConsoleAccountEvents(Account a){
account = a;
}
}
Here the parameter "a" is defined to be of the Account "type" - the argument sent to the constructor must be an instance of the Account class, in other words the constructor requires an Account object. So in order to construct a ConsoleAccountEvents object we must pass it an Account object as the argument as such:
Account acct = new Account();
ConsoleAccountEvents c1 = new ConsoleAccountEvents(acct)
Using "new" calls the constructor of the following class. For the Account class, we need no arguments to create an object - it has a default constructor, but we need to use an Account object - acct - as the argument to allow ConsoleAccountEvents to be constructed since it's constructor has an Account type parameter in it's definition.
In other languages there are more ways to construct objects. In C++ for example, the programmer can choose which objects should be saved on the "heap" and the "stack" by switching between using the new keyword vs calling the constructor directly as if it was any other function. In Java this is not possible. Almost all objects are created using the new keyword or by copying another object in some way. I believe even serializing and deserializing had to start with new at some point to create the first object.

what is the extra benefit of creating constructor in java?

I have noticed a thing that a constructor and a simple method of a class do the same work. what is the exact reason to create a construct of a class? If i create MyClass(){} constructor and MyClassMethod(){} method it will do the same work as I write the body part of those method and constructor. So what is the need of construct? Does it have any special use ?
A constructor and a method are two different things. The fact that you can write the same or similar code inside them is irrelevant.
When a new object is created a constructor is called. If you don't specify one the compiler will create a default one for you. This is the place where initializaton of the object's fields takes place and memory is allocated for the object. This is a concept that all object-oriented languages have. A new object must be initialized somehow. Memory needs to be allocated. In Java you don't manage the memory yourself (at least not directly anyway) so this is the purpose of the constructor. Note that since a constructor is always executed, this behaviour is enforced as soon as you call e.g. Person p = new Person();.
Now since a constructor is always being called, you have an option here: do you let the default constructor execute or do you create one yourself? Perhaps there are fields that need to be initialized in a way other than their default values. Or perhaps you need to not allow creating an object without providing some values. If you define a constructor yourself, the compiler does not create a default one for you. So if I have public Person(String firstName, String lastName) {} then I have created a specific rule that is again enforced by the system: a new object of class Person cannot be created unless you give a first name and last name:
Person p = new Person(); // this would give a compile error
Person p = new Person("John", "Smith"); // this is the only way to create an object now
Using a method you cannot enforce this. The programmer using your class might call your method or not. The constructor is a part of the lifecycle of the object. Methods define the behaviour of the object
Some points :
1) Constructors are the only way to set final instance variables .
public class SomeType {
final int x ;
SomeType(int y){
x=y;
}
}
2) A class with private constructor cannot be sub classed.
3) If your class is a subclass and the base class doesn't have a default constructor , then you need a constructor in your class to call the super class constructor.
One of the benefits of using a constructor over a method is that you can be assured the constructor was called and the work within the constructor was performed.
The language specifies that to construct an object a constructor must be called. So if you use a custom method to establish the initial state of your object, you will need to call the default constructor first. Why make two method calls when you can perform the work in one call the constructor and be assured the object has been properly initialized?
public class Test(){
private Integer x;
public Test(){
}
public Test(Integer x){
this.x = x;
}
public void setX(Integer x){
this.x = x;
}
public void doSomethingWithX(){
this.x.toString();
}
}
Test test = new Test(8);
test.doSomethingWithX(); //I know x has been declared and assigned
Test test = new Test();
test.doSomethingWithX(); //X has not been assigned results in NPE
If you create a new Object of MyClass it will automatically call the constructor - you can initialize all members within it, and be sure that this object´s members are all initialized.
Generally:
A constructor is always called once when you create a new Object of this class, and you can´t call it manually.
And don´t do "real" work in a constructor, as it will slow down the creation of objects of this class - only initialize your class/members there.
You can also use different constructors, depending on your needs - but if you create a constructor, there is no more default constructor!
Example:
public MyClass {
int score;
public MyClass(int sc) { // already know the score
score = sc;
}
public MyClass() { // don´t know the score yet
score = 1;
}
public void addScore() {
score += 5; // i know for sure that score is not zero
}
}
Essentially a constructor is just a special method that implicitly returns an object of its containing type. You should generally use constructors for creating objects - this is what people expect to see.
However, there is a useful idiom called the factory method (more info at this link) which is essentially using a static method to construct an object, the key advantages being
You can give a factory method a more descriptive name (whereas of course a standard constructor has to be named after the containing class).
They don't have to return an object, giving more flexibility.
They can return a sub-types of the class.
You can set final fields without initializer in a constructor. This helps to build immutable instances:
class Number extends Expr {
private final int n;
public Number(int n) {
this.n = n;
}
public int getValue() {
return this.n;
}
}
So after a constructor like this, you can rely on the fact that the instance is initialized completely (and in this case, it's values are immutable/constant).
Constructor is not like simple methods. It is called every time when the object of that particular class is created. You don't need to call it explicitly.
There are somethings that we need to do immediately when the object is created, for instance when you create a GUI kind of thing you want to set many properties on the time of creation like size of window etc.
Another benefit of constructor is security of class. You cannot create a object unless you know the right perimeters of constructor.
More details:http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
A constructor is a special method of a class or structure in object-oriented programming that initializes an object of that type.
Some points :
1. A constructor eliminates placing the default values.
2. A constructor eliminates calling the normal method implicitly.
These are the benefits of constructors.
Automatic initialization of objects at the time of their declaration.
Multiple ways to initialize objects according to the number of
arguments passes while declaration.
The objects of child class can be initialised by the constructors of base class.

How does Object Oriented Programming work?

I am not sure about some things in OOP.
If I have Class1, which has some private field, for example private Field field1, and make
getField1 () {
return field1;
}
then I have some class with constructor
public Class2 (Field field) {
someMethod(field);
}
And then I call constructor of Class2 in Class3 like:
Class2 cl = new Class2(instanceOfClass1.getField1());
And now the question: Am I working with field1 of instanceOfClass1 in someMethod(field)?
This depends on whether field is a value or a reference.
Value types are copied when passed as parameters. Reference types are not; the function is simply handed a "reference" that points back to the original value, and any changes that it makes are reflected in the original value.
Whether a given type is value or reference depends on your particular programming language. Generally speaking, basic integer and boolean types are usually value types, and everything else is up in the air -- some languages make strings values, and others treat them as references, etc.
Edit: Since you mentioned you're using Java, here's a short program that demonstrates value and reference types:
class ClassOne {
public int myInt;
}
class ClassTwo {
public int myInt;
public ClassTwo(ClassOne c)
{
myInt = c.myInt;
c.myInt = 3;
}
}
public class main
{
public static void main(String[] args)
{
ClassOne c = new ClassOne();
c.myInt = 1;
System.out.println("C1: " + c.myInt);
ClassTwo c2 = new ClassTwo(c);
System.out.println("C2: " + c2.myInt);
System.out.println("C1: " + c.myInt);
}
}
Running this program will give the output:
C1: 1
C2: 1
C1: 3
In this program, both ClassOne and ClassTwo contain an integer field -- a value type. ClassTwo takes a ClassOne parameter -- a reference type -- in its constructor, and sets its own integer field based on the value of the ClassOne object it is given, and then changes the ClassOne object's value.
Because classes are reference types, changing the ClassOne object in the ClassTwo constructor causes the original object to be changed. (In the main function here, that's c.) But because integers are value types, even though c2 changes the value of c.myInt in its constructor, because it sets its own value beforehand, c2.myInt isn't affected: it retains the original number, because it was copied rather than referenced.
Hopefully this helps clear things up a bit.
You're working with the value contained in it. If it is a mutable object then yes, it is possible to change the state of the instance of Class1 from outside, which violates data protection principles. This is why you should copy mutable types before returning them.
I had to reread your question two or three times to make sure I understood what you're asking.
To recap:
There is Class1 which contains an field attribute (of type Field?) which is sent back by it's getField1() method.
There is then Class2 which is apparently has a constructor that accepts an object parameter of Field type and contains a method that uses an instance of Field to trigger a local method in this class.
You then use a third class to instantiate Class2 and initialize it using an instance of Field using the getField1() method from an instance of Class1.
In the case of Java, providing you've done the necessary instantiation this would mean that the Field instance in Class1 is being used throughout the process. You can verify this using a System.out.println() (this will give you an # symbol with a series of weird numbers) or using the a.equals(b) method common to all objects.
Here is an interesting link about passing objects by value:
http://www.javaranch.com/campfire/StoryPassBy.jsp

Categories