0

I have started to learn OOP and I understand the concept of a class, I understand that by using constructors we can shield our class from the rest of the program but I would like to know more about the relationship between the class and its constructor.

When I set up a constructor, it is initializing my instance variables but is it duplicating my class and then I am dealing with just the constructor or is it being used as an intermediary between my class and the rest of my program i.e does it pass information into the class?

Here is an example of a program I made last week.

class Pets

{

private String breed ;
private String coat ;
private String temperment ;

//constructors with 3 parameters and 3 instance variables.
public Pets ( String aBreed, String aCoat, String aTemperment )

{

breed = aBreed ;
coat = aCoat ;
temperment = aTemperment ;

}

//Setters
public void setBreed ( String aBreed ) { breed = aBreed ; }
public void setCoat ( String aCoat ) { coat = aCoat ; }
public void setTemperment ( String aTemperment ) { temperment = aTemperment ; }


//Getters
public String getBreed() { return breed ; }
public String getCoat() { return coat ; }
public String getTemperment() { return temperment ; }

//petDisplay - A method to print information about pets.
public void petDisplay()

{

System.out.println ( "This pet is a " + breed + ", it has a " + coat + " coat and is " + temperment + "." ) ;

}
Ninja2k
  • 819
  • 3
  • 9
  • 34
  • 1
    The constructor is used to construct instances of the class. When you say `new Pets`, that invokes the constructor to create an instance. – Elliott Frisch Mar 20 '17 at 20:40
  • https://msdn.microsoft.com/en-us/library/s16xw1a8.aspx – OldProgrammer Mar 20 '17 at 20:41
  • A constructor is not a separate entity. It is a specific method for a class that is called when an object type of that class is instantiated. It does not " shield our class from the rest of the program ". – OldProgrammer Mar 20 '17 at 20:43
  • 1
    *"does it pass information into the class?"* Yes, it does. And you should use it to assign its parameters to the instances variables and/or the super constructor. A constructor should not do anything else (except basic validation). In particular it should not instantiate other classes (use the `new` operator) or call methods on the objects passed in. – Timothy Truckle Mar 20 '17 at 20:44
  • That is what I was looking for Timothy. I don't understand why my question is being flagged for closure, simply stating the constructors purpose does not describe how information is being used. – Ninja2k Mar 20 '17 at 20:46
  • Perhaps first, there's some confusion between classes and objects. [This](http://stackoverflow.com/a/1486212/474287) is a nice explanation of the differences between the 2 OOP concepts. From this point on, you already have some answers explaining what constructors are used for... – Morfic Mar 20 '17 at 20:50
  • To fully understand the purpose of constructor, please look up the term "invariant" (https://en.wikipedia.org/wiki/Invariant_(computer_science) ). Constructor's purpose is to set the class member variables so that the invariant is true. –  Mar 20 '17 at 20:55

4 Answers4

1

The constructor is not a way to use your instances, but rather the way they should start before they are used.

For exemple, in your code, what you are saying to all future coders that will use your class is that, if they want a pet, they HAVE TO provide a breed, a coat and a temperment. This is a way to make sure that there will be no bad uses of your class.

Then, you have the getters and setters, that are used to access a class properties.

Finally, the methods are used to provide calculations and treatments.

Now is the really good part : as you can write your constructor as you want, you should not assign a property directly but use the setter whenever it is possible.

Why ? Because this way, you can check the validity of your datas and reject them if they are bad for your class. Here is an exemple :

public void setBreed(String aBreed)
{
  if(aBreed == null)
  {
    System.out.print("You should give a breed !");
  }
  else
  {
    breed = aBreed;
  }
}

and your constructor will become

public Pets ( String aBreed, String aCoat, String aTemperment )
{
  setBreed(aBreed) ;
  setCoat(aCoat) ;
  setTemperment(aTemperment) ;
}

This way your code will be more robust and you will see less errors ! To be fair, you should use Exceptions to tell this kind of mistakes (ArgumentNullException for exemple) but this is for another question.

It's important to know that default constructors are often used for a variety of reasons. Then, I have the habits of adding a default constructor whenever possible.

public Pets()
{
  this("Breedless","Grey","WhateverIsATemperment");
}

Have a nice day !

Augustin Bocken
  • 379
  • 4
  • 18
  • We have learnt this in lesson 2, they just wanted to introduce the fundamentals, I am coming from a C background and I like to understand exactly what is happening in memory. – Ninja2k Mar 20 '17 at 20:56
  • Sometimes, you need to stop caring too much about the memory, as the JVM will do things sligthly differently depending of the machine... But I understand why you would ask the question. Just remenber about the Garbage Collector and try to write without using too mush ressources if you can, and you'll be fine – Augustin Bocken Mar 20 '17 at 20:59
  • It is more so for my understanding of how OOP works, I think one of the reasons starting off in C is better is that you understand what is happening, most of my class can program in Java but they don't know what is actually happening, like when we covered arrays they did not understand how that was being handled in memory as I did. It is not necessary to understand the concept but it is necessary to master the concept. – Ninja2k Mar 20 '17 at 21:05
  • 1
    @Ninja2k: an interesting observation r.e. lower level understanding. I was going to talk about what you can learn from 'writing object-style code in C' but this is stackoverflow, so of course there is already an awesome answer: http://stackoverflow.com/questions/351733/can-you-write-object-oriented-code-in-c#351756 – jgreve Mar 20 '17 at 21:39
  • Here, I found that for you, maybe it can answer your question : http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value?rq=1 – Augustin Bocken Mar 23 '17 at 11:10
0

The constructor in java is a special type of method that is used to initialize the object.

Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as the constructor.

it have some rules to follow up when declaring it

  1. Constructor name must be same as its class name
  2. Constructor must have no explicit return type

you can overload it to specify different initialize to your instances

  • A constructor is not "a special type of method", as it is not any type of method. – Lew Bloch Mar 20 '17 at 20:51
  • I said a special type of method as it is like method in everything but has no return type try to revision docs of contractors –  Mar 20 '17 at 20:56
  • You said a constructor "is a special type of method". It is not. It is not like a method "in everything". A constructor establishes a memory barrier on completion; a method does not. A constructor initializes an object; a method does not. A constructor has access to partially-initialized state; a method unless called from a constructor does not. A method has a return type, a constructor does not. A constructor must appear after `new`, a method may not. They have completely different purpose, semantics, and major sections in the JLS. They are not at all the same. It is wrong to say otherwise. – Lew Bloch Mar 20 '17 at 21:18
  • can you check `http://www.javatpoint.com/constructor` it is the same as i said :) –  Mar 20 '17 at 23:10
  • I'll stick with what the Java Language Specification says, given that it actually defines the language. – Lew Bloch Mar 20 '17 at 23:48
  • that tutorial got a few things wrong. Don't use it as an authority. First, it calls a constructor a type of method. It is not. Second, it refers to any no-arg constructor as a "default" constructor, and that is wrong. Only the constructor _provided by the compiler_ when the class doesn't have one is the default constructor. Third, it claims the "default [sic]" constructor provides the default values to member variables; it does not. `new` does that. So that link is garbage. – Lew Bloch Mar 20 '17 at 23:56
  • yeah, thank you ,can you recommend for me a tutorial that I can trust in? –  Mar 22 '17 at 16:37
0

"I understand that by using constructors we can shield our class from the rest of the program " is not correct. Constructors do not exist to "shield" anything, whatever that means.

Constructors are initializers; they exist to set up the initial state of an object. You can pass data to constructors, but do not make the mistake of passing operational data; pass data needed for setting the initial state.

Don't put business logic in a constructor. Business logic should apply only to fully-constructed objects. Getting into it within a constructor is a recipe for weird, expensive bugs. This is dectuply true where threads are involved. Construct first, operate second.

A constructor is not for "duplicating my class ", it's for initializing an instance of the class.

Lew Bloch
  • 3,364
  • 1
  • 16
  • 10
  • That is the general explanation of what a constructor is but it does not describe what is actually happening with the data,Timothy Truckles answer is what I was looking for, it does pass information rather than duplicating the classes variables. – Ninja2k Mar 20 '17 at 20:54
  • Well, it picks up the values from its parameters, which could be pointers to the same objects as passed. I have no idea what you mean by "duplicating the classes [sic] variables". It's not an "intermediary", and as I said, it does not "duplicate a class". Also, as I said, it can accept data. I can only answer the question you actually asked. – Lew Bloch Mar 20 '17 at 21:14
0

As has been mentioned, the constructor is used to create an instance of the class. Looking at your code, you have a method to print information about pets, as all classes are subclasses of the Object class, you can use the toString method to print out information from your class. You can do something like this to be specific for your Pets class:

@Override
public String toString() {
  return ( "This pet is a " + getBreed() + ", it has a " + getCoat() + " coat and is " + getTemperment() + "." );
}

Note: @Override does not need to be there, but can be good practice.

JLW
  • 9
  • 4
  • The constructor does not "create an instance of the class"; `new` does that. The constructor _initializes_ the instance after it is created. – Lew Bloch Mar 20 '17 at 23:57