Results 1 to 3 of 3
  1. #1
    Renxx is offline Member
    Join Date
    Oct 2011
    Posts
    16
    Rep Power
    0

    Default Why my constructor doesn't initialize these values?

    Java Code:
    class BicycleDemo  {
    	public static void main (String[]args) {
    		
    		// Loon kaks erinevat jalgratta objekti
    		Bicycle bike1 = new Bicycle(3,5,10);
    		//Bicycle bike2 = new Bicycle();
    				
    		//kasutan objektidel BicycleDemo meetodeid.
    		bike1.printStates();
    		bike1.changeCadence(10);
    		bike1.changeGear(1);
    		bike1.speedUp(20);
    		bike1.printStates();
    		bike1.applyBrakes(5);
    		bike1.printStates();
    		
    		
    
    	}
    	
    }
    
    class Bicycle extends BicycleDemo {
    	
    	int cadence ;//Object's state
    	int speed ;
    	int gear ;
    	
    	//Konstruktor 1
    	Bicycle (int sCadence,int sSpeed,int sGear) {
    		sCadence = cadence;
    		sSpeed = speed;
    		sGear = gear;
    	}
    	
    	void changeCadence (int newValue) {
    		cadence =newValue;
    	}
    	
    	void changeGear (int newValue) {
    		gear = newValue;
    	}
    	
    	void speedUp (int increment) {
    		speed = speed + increment;
    	}
    	
    	void applyBrakes (int increment) {
    		speed = speed - increment;
    	}
    	
    	void printStates() {
    		System.out.println("Speed:" +speed+", gear:"+gear+",cadence:"+cadence);
    	}
    }

    I have set my constructor Bicycle(3,5,10), but printStates still gives value for speed,cadence and gear 0,0,0.

  2. #2
    Iron Lion is offline Senior Member
    Join Date
    Nov 2010
    Posts
    210
    Rep Power
    5

    Default Re: Why my constructor doesn't initialize these values?

    Java Code:
        Bicycle (int sCadence,int sSpeed,int sGear) {
            sCadence = cadence;
            sSpeed = speed;
            sGear = gear;
        }
    You have your assignment statements the wrong way round. You're assigning the value of the instance variable to the argument variable, when you intend to do the opposite.

  3. #3
    Renxx is offline Member
    Join Date
    Oct 2011
    Posts
    16
    Rep Power
    0

    Default Re: Why my constructor doesn't initialize these values?

    Thank you ;). How i couldn't see that :)

Similar Threads

  1. Assigning array values to objects in a constructor
    By Dreaming in forum New To Java
    Replies: 8
    Last Post: 10-25-2011, 07:17 PM
  2. why constructor doesn't have any return type?
    By kaka in forum New To Java
    Replies: 1
    Last Post: 09-30-2010, 09:02 PM
  3. HashMap contains all values but doesn't show all values
    By xcallmejudasx in forum New To Java
    Replies: 3
    Last Post: 05-11-2009, 12:35 AM
  4. Replies: 16
    Last Post: 05-08-2008, 10:45 PM
  5. Replies: 0
    Last Post: 12-19-2007, 10:10 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •