object oriented programming, constructor with parameters - java

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.

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.

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.

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.

instance variable in another class

I'm working on homework and I won't post the full code but I'm stuck on something that's probably simple and I can't find it in my book so I need to be pointed in the right direction.
I'm working with classes and interfaces.
Basically in my main code I have a line like this
CheckingAccount checking = new CheckingAccount(1.0); // $1 monthly fee
I was told to create a class called CheckingAccount and in that class I am told "This class should include an instance variable for the monthly fee that's initialized to the value that's passed to the constructor.
Since I'm new this is barely english to me and I'm assuming what that is saying is to take that 1.00 fee and declare it in the CheckingAccount class so I can create a method using that variable to calculate something.
soooo... How do I do that? I know how to create an instance variable it would be something like
public double monthly fee =
but then what? or I could be wrong. I am really doing bad at this java stuff. Any help is appreciated.
I guess another way to ask it is am I just declaring it as 1.0? or am I "importing" that value in case it changes later at some point you don't have to go through the code to change it in all of the classes?
Your requirement (as I read it) is to initialize the instance variable in the constructor, and your instantiation (new CheckingAccount(1.0);) shows you are on the right track.
What your class will need is a constructor method which receives and sets that value 1.0.
// Instance var declaration
private double monthly_fee;
// Constructor receives a double as its only param and sets the member variable
public CheckingAccount(double initial_monthly_fee) {
monthly_fee = inital_monthly_fee;
}
#Jeremy:
You're pretty much spot on (at least, your interpretation of what you've been asked to do matches my interpretation); while I don't know the actual design of the class, or whether monthly_fee needs to be public, in pseudocode you'd be looking at something like:
class CheckingAccount {
//Instance variable
double monthly_fee;
//Constructor
CheckingAccount(double monthly_fee) {
this.monthly_fee = monthly_fee;
}
//Function to multiply instance variable by some multiplier
//Arguments: Value to multiply the monthly fee by
double multiply_fee(double a_multiplier) {
return monthly_fee*a_multiplier;
}
}
You are basically right. If you haven't already, you should create a new class (it should be in it's own file called CheckingAccount) like this:
/** This is the class of Account with monthly fee. */
public class CheckingAccount {
// This is the instance variable.
// It should be 'private' for reasons you will surely learn soon.
// And NOT static, since that would be a class variable, not an instance one.
// The capitalization is called camelCase, google it up. Or, even better, find 'JavaBeans naming conventions'
private double monthlyFee;
// This is the constructor. It is called when you create the account.
// It takes one parameter, the fee, which initializes our instance variable.
// Keyword 'this' means 'this instance, this object'.
public CheckingAccount(double monthlyFee) {
this.monthlyFee = monthlyFee;
}
// Here will be your methods to calculate something...
}
Don't create an instance variable as public. It's bad practice because it violates the principle of information hiding (your teacher may call this abstraction). Instead, you can create an instance variable as
public final class CheckingAccount {
private double monthlyFee;
// The rest of the class goes here
public double getMonthlyFee() { // This method is called an accessor for monthlyFee
return monthlyFee;
}
}
Note that monthly fee isn't a valid variable name because it contains a space, and variable names can't contain spaces. Also notice that other classes access monthlyFee through a method. Because you define the method rather than making the variable public, you control access to monthlyFee a lot better (another class can't just change monthlyFee unless you define a method that makes that change).
Now to accessing monthlyFee. The method getMonthlyFee is called an accessor for a reason: it allows other classes to access that variable. So, those other classes can just call the method to get the monthly fee out of a CheckingAccount:
CheckingAccount checking = new CheckingAccount(1.0);
// A bunch of other code can go here
double fee = checking.getMonthlyFee(); // Now fee is 1.0

Categories