...

View Full Version : What is wrong with this piece of code?



dannyboi
07-26-2012, 02:21 AM
In Java
public class Main
{

public static void main(String[] args)
{



Ball b1 = new Ball ();
Ball b2 = b1;

b1.setSpeed(50);
b2.setSpeed (100);
int speed = b1.getSpeed();
}

}
}

alykins
07-26-2012, 12:03 PM
no clue- what error message are you getting? what is 'wrong' with it? what does the 'Ball' class look like... assuming that Ball has those properties, and also assuming that Ball has those methods... (and assuming this is C# and not Java)



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace testing
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("start...");

Ball b1 = new Ball();
Ball b2 = b1;

b1.setSpeed(50);
b2.setSpeed(100);
int speed1 = b1.getSpeed();
int speed2 = b2.getSpeed();

Console.WriteLine("Speed of first ball (b1) is {0}", speed1);
Console.WriteLine("Speed of second ball (b2) is {0}", speed2);

Console.WriteLine("fin...");
Console.ReadLine();
}
}

public class Ball
{
private int _speed;

public Ball()
{
this.setSpeed(0);
}

private int speed
{
get
{
return _speed;
}
set
{
_speed = value;
}
}

public void setSpeed(int i)
{
this.speed = i;
}

public int getSpeed()
{
return this.speed;
}
}
}




Now because b2 is not declared as new Ball() it will output
start...
Speed of first ball (b1) is 100
Speed of second ball (b2) is 100
fin...


but by declaring b2 as a new Ball (and thus new object and new resources)



// change this
Ball b1 = new Ball();
Ball b2 = b1;

// to this
Ball b1 = new Ball();
Ball b2 = new Ball();




the output would then be
start...
Speed of first ball (b1) is 50
Speed of second ball (b2) is 100
fin...


But, without more information- I am just shooting in the dark



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum