Don't understand the link between constructor and object - java

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.

Related

When exacty is the object initialized?

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.

Why we are creating variable of type of class?

First Line we can use for create object, in which scenario we can use 2 and 3?
Test test =new Test();
Test test =null;
Test test ;
You clearly don't "know" the following "ways" to create an object, since only one of your "ways" actually does (assuming the proper semicolon is added to allow the line to compile).
Test test = new Test();
That is the only way to actually create an object in direct Java syntax. Object creation can be obfuscated by methods that use the new keyword behind the scenes, but it boils down to using the new keyword and a constructor invocation.
Test test = null;
Setting this variable to null doesn't create anything but a holder for a Test object named test. But null is not an object and nothing is created.
Test test;
This line does the same thing as setting test to null in a class, but in a method it allows the declaration for the holder to allow it to be set in another line further down. However, you will get a syntax error if the Java compiler can't figure out a path that you actually set this variable prior to it being read in further code. To get around this error, you can set it to null at the beginning like the previous line.
The first way actually creates an instance called Test and assigns it to the variable test.
Test test =new Test(); // ' ; ' missing
The second only assigns a null pointer to test.
Test test =null;
The third way does not assign anything to test, unless it is an instance variable in which case it will assign a value of null to it.
Test test ;
Test test;
in this case , didn't make object. this only create test variable in stack. it is Type is Test object type.
Test test=null;
in this case you assign null value to that referens.
Test test =new Test();
this mean ,you crate new object in class Test.this object made in heap.
I think this is basic thing java. you do further research.
thank you.
public class Test{
int a ;
public Test(){
}
public class Test(int a){
this.a = a ;
}
public static void main(String args[]){
//To define a variable of type Test
Test t ;
//Defining another variable of type Test
Test t2;
//To instantiate an object of type Test using no argument constructor
//Now t holds a reference to object created by new Test()
t = new Test();
//Pass the Object reference in t to t2 variable
t2 = t ;
//To instantiate an object using one argument constructor Test(int a)
//Now t will hold reference to object created by new Test( 2)
//That makes old Test instance created by no argument constructor eligible to be cleanedup by garbage collector
t= new Test(2);
//now to release the reference to object created by new Test(2) , we set null
//In better words, we are setting the reference to "null", so that variable t no longer point to the test instance"
//For better understanding, search for database/JDBC programming example to see how we use "null" in finally block
t = null;
}
Generally null is used to dereference any of the objects referenced by the particular variable.

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.

Categories