Adding the Class instance name to an output string
Greetings all,
I am working on a college project I will tell you that up front. I have completed the project to create a car class and to have it accelerate and brake. My question does not involve any part of the actual assignment requirement, but I wanted to add a method that would allow me to print the attributes and when it prints I wanted it to add the name of the instance to the print statement
for example: I have a class called CarClass and I create new instances as follows:
CarClass newName = new CarClass("color","make","model","year","owner");
I have created a couple of classes as such:
CarClass firstCar = new CarClass("Red","Chevy","Malibu","2005","Bob");
CarClass secondCar = new CarClass("Blue","Saturn","Aura","2007","Sandy");
I have a printAttrbutes method in the CarClass that will do the following:
public void printAttributes()
{
System.out.printf("%s owns a %s %s %s, myOwner, myYear, myMake, myModel);
}
all of that works fine but I am trying to make the print statement include the name of the CarClass instance for example:
if I were to print the attributes about the secondCar I would like to print: secondCar is owned by Sandy and is a 2007, Saturn Aura
I am not sure how to get it to add the instance name to the print string.
I hope what I am asking is clear enough, if not please reply or shoot me an email and I will respond.
thanks
Wally
Re: Adding the Class instance name to an output string
As far as I know, the name you give the object is not now to the object. The only way to do this is to hardcode it in.
Re: Adding the Class instance name to an output string
A reference variable (aka identifier) is in no way an 'instance name' and doesn't exist at runtime.
Objects don't have names (unless of course the class has a name attribute, but that's another story).
db
Re: Adding the Class instance name to an output string
Interesting. I have never thought of it that way. Thanks for the feedback. Gives me food for thought. I was just trying to make it more intuitive when the user was looking at the output. The user being the teacher :)