I don't understand constructors. Can anybod help?

The question is:

You are given a classnamed Clock that has one intinstance variable called hours . Write a constructor with no parameters for the class Clock . The constructor should set hours to 12 .

I think the answer is:

hours=12;

but I'm worng. Please help.

P.S. One more question:

How do you compare Strings. I think you do:

compareTo(string1,string2)>1;

Am i correct? :rolleyes:

Thanks

I figured out the string stuff ( string1.compareTo(string2)>0; )

Can you just help me on constructors?

Thanks
-- C++

A constructor in essance is a method (with the same name as the Class) that is executed when an instance of the class is created.

For Example:

public class foo {

   public int x;

   // Constructor
   public foo() {
        // Do something like
        this.x = 45;
   }

}

So when you enter in your application:

foo x = new foo() the constructor foo() is executed.

Thanks.

One more question:

You are given a classnamed Clock that has three instance variables: One of type int called hours , another of type boolean called isTicking , and the last one of type Integer called diff . Write a constructor for the class Clock that takes three parameters -- an int , a boolean , and another int . The constructor should set the instance variables to the values provided.

I think the answer is:

public Clock(int hours, boolean isTicking, int diff){
this.hours = hours;
this.isTicking = isTicking;
this.diff() = diff;
}


Thanks!

Yep, that would be it.

Opps......this.diff()....should be .......this.diff

i still get more errors

Looking at your code:

public Clock(int hours, boolean isTicking, int diff){
    this.hours = hours;
    this.isTicking = isTicking;
    this.diff = diff;

You should have hours, isTicking, and diff defined as class variables too. I did not see that in your code snippet.

To prevent confusion between class variables, and local (method) variables, I add an underscore to my private variables, so that I don't get them confused......ie:

public class CLock {
   // Private variables to the class
   private int hours_;
   private isTicking_;
   private diff_;

    // Your constructor
    public Clock(int hours, boolean isTicking, int diff){
        this.hours_ = hours;
        this.isTicking_ = isTicking;
        this.diff_ = diff;
    } // End of Clock Constructor
} //End of Clock Class

Hoope this clarifies things. If not, submit what errors you are receiving and the code.

My error message is:

Clock.java:11: incompatible types
found : int
required: java.lang.Integer
this.diff=diff;
^
1 error

Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.