1

i am new to java and i have a simple question and i have this code

public abstract class Seq { int a, b, c;}

class For extends Seq{
public For( int first, int last, int step )
{
a=first;
b=last;
c=step;
}

and in the main i have:

For r1= new For(3, 4, 5);

what i want to do is that i want to add this statement in the main System.out.print(r1); and i want this statement to print "your parameters: 3, 4, 5"

how can i do this?

CSawy
  • 864
  • 1
  • 12
  • 24
  • I would take a read through [How to use the toString method in Java?](http://stackoverflow.com/questions/3615721/how-to-use-the-tostring-method-in-java) – MadProgrammer Nov 13 '12 at 04:42

5 Answers5

4

Add a toString method in For as:

@Override
public String toString(){
    return "your parameters: "+ a + ", "+ b+ ", "+c;
}
Yogendra Singh
  • 33,197
  • 6
  • 61
  • 72
2

You can do this by implementing the For class' toString method:

public String toString ( )
{
    return "your parameters: " + a + ", " + b + ", " + c;
}
Mac
  • 14,385
  • 9
  • 62
  • 78
0

You would have to override the toString() method and create another one that prints out the contents of r1.

@Override
public String toString(){
    return a + ", " + b + ", " + c;
}

Then it is simply:

System.out.println("Your parameters: " + r1.toString());

yiwei
  • 3,692
  • 9
  • 33
  • 53
0

From Java Doc for String

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

So if you want to your representation for For object then you have to override toString() in your class Like folowing :

class For extends Seq{
  public For( int first, int last, int step )
   {
     a=first;
     b=last;
     c=step;
   }
 @Override
 public String toString(){
    return "your parameters: "+ a + ", "+ b+ ", "+c;
 }
}
Sumit Singh
  • 24,095
  • 8
  • 74
  • 100
0

Make a public string that returns

return a + ", " + b + ", " + c;
MrAwesome8
  • 269
  • 1
  • 2
  • 9