Domanda

I am referencing Y. Daniel Liang's book "Introduction To Java Programming, Comprehensive Version, Ninth Edition" when I ask this question. Every time I see an object created by using a constructor, it goes something like this :

Car engine = new Car(). 

But in Daniel Liang's book, I found the following code (only the first 9 lines written here):

   public class SimpleGeometricObject {
      private String color = "white";
      private boolean filled;
      private java.util.Date dateCreated;

      /** Construct a default geometric object */
      public SimpleGeometricObject() {
         dateCreated = new java.util.Date();
   }

What I don't understand is how come the object "dateCreated" is not created in the normal way, ie.:

SimpleGeometricObject dateCreated = new SimpleGeometrciObject();

I'm confused.

È stato utile?

Soluzione

Actually dateCreated is an Object from the Class Date which is in package java.util and is inside the Object you are defining which is SimpleGeoMetricObject

In other words Java guys wrote this:

  package java.util;

 public Class Date{
    //with its own attributes 
   public Date(){
      ...
    //and its own constructor
   }
     ...//and it's own methods
}

And provided it to developpers so we can use it in our own Class/Objects and by the way if you import the package like this import java.util.Date; in the beginning of your file you would only need to construct Date like follows : Date objectDate = new Date();

Altri suggerimenti

dateCreated is only an attribute / variable of SimpleGeometricObject. So the dateCreated is of type Date, and you technically call the constructor of this using:

dateCreated = new java.util.Date();

You do not need this:

java.util.Date dateCreated=new java.util.Date();

Because the dateCreated field data type is already defined in:

private java.util.Date dateCreated;

So, basically:

 private java.util.Date dateCreated 

defines the datatype but initializes to null and

 dateCreated=new java.util.Date();

initializes the default value to the dateCreated object

He has simply used the complete qualified name for the Date class, including the package name "java.util". Based only on what we see here, there is no reason for him to have done this. The only real justification would be if there is another class, in another package, also called Date, and he needs to be able to distinguish the two. Or perhaps he's just making a point for some reason, that the Date class is in that particular package.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top