I want to add a toString method in the Item class that returns the title of the item in there.
I have need make sure that the toString method in the DVD class calls the toString method in Item so that it can return a string that contains both the title and the director.
Item is the superclass and DVD is the subclass.
public class Item
{
private String title;
private int playingTime;
private boolean gotIt;
private String comment;
public Item(String theTitle, int time)
{
title = theTitle;
playingTime = time;
gotIt = false;
comment = "<no comment>";
}
// Getters and setters omitted
public void print()
{
System.out.print(title + " (" + playingTime + " mins)");
if(gotIt) {
System.out.println("*");
} else {
System.out.println();
}
System.out.println(" " + comment);
}
}
public class DVD extends Item
{
private String director;
public DVD(String theTitle, String theDirector, int time)
{
super(theTitle, time);
director = theDirector;
}
// Getters and setters omitted
public void print()
{
System.out.println(" director: " + director);
}
}
Item toString:
public String toString()
{
return title;
}
DVD toString:
public String toString()
{
return super.toString() + " director: " + director;
}
Also, I don't know what you're trying to do with this but I would put those print() methods in these classes.
You will be better of returning the string representation and printing it somewhere else (with this you can test this class without mocking System.out)
Cheers
A toString method is already defined in each Java class (it inherits the toString of Object). But it will return a practically meaningless value (AFAIR, the internal address/id of the instance within the JDK - I might be wrong).
What you need to do is to override that method and make it return a String that is the title of the Item. For the DVD class, you have to override toString and make it a string made up of the concatenation of the title and director.
For the Item class, your method should look something like this:
public String toString(){
return this.title;
}
You should be able to use the same idea to implement toString for DVD.
Related
I have an abstract class, Mower, that overrides the toString() method. The Lawn Tractor class extends Mower. It overrides the toString() method and calls super.toString() as the first line in the method. I then have a Commercial class that extends LawnTractor and overrides the toString(), calling super.toString() in its first line as well.
When instantiate a Commercial object (declared as a Mower object) and call its toString() I expect it to print both properties from Mower and Lawn Tractor and then it's own properties. Instead, it prints only the properties from Mower and then it's own properties. How do I call or override the toString() method in Commercial so that it calls its parent (LawnTractor) toString() and not just the super class (Mower).
public abstract class Mower {
private String manufacturer;
private int year;
private String serialNumber;
public String tostring(){
String temp = "Manufacturer: " + getManufacturer() + "\nYear: " + getYear() + "\nSerial Number:" + getSerialNumber() + "\n";
return temp;
}
}
public class LawnTractor extends Mower{
private Engine engine = new Engine();
private String model;
private double deckWidth;
public LawnTractor(){
super();
}
public String toString(){
String temp = super.tostring() + "Engine:\n" + getEngine().toString() + "\nModel: " + getModel() + "\nDeck Width: " + getDeckWidth() + "\n";
return temp;
}
public class CommercialMower extends LawnTractor {
private double operatingHours;
private boolean zeroTurnRadius;
public CommercialMower(){
super();
}
public String toString(){
String temp = super.toString() + "Operating Hours: " + getOperatingHours() + "\nZero Turn Radius: " + isZeroTurnRadius() + "\n";
return temp;
}
So it sounds like you are trying to do is create a hierarchy of toStrings to print when you have a graph of objects. So all you need to do is append the super's toStrings as they are called up the chain. (If I'm understanding you correctly)
Here's the Mower class
public class Mower {
#Override
public String toString() {
return "Mower toString\n";
}
}
LawnTractor
public class LawnTractor extends Mower {
#Override
public String toString() {
String superString = super.toString();
return superString + "LawnTractor toString\n";
}
}
Commercial
public class Commercial extends LawnTractor {
#Override
public String toString() {
String superString = super.toString();
return superString + "Commercial toString\n";
}
}
Main class to run it. See the output below. Is this where you are going with this.
public class Main {
public static void main(String[] args) {
Mower mow = new Commercial();
System.out.println(mow.toString());
}
}
Here's your output. I believe this is what you're looking for. If not please clarify
Mower toString
LawnTractor toString
Commercial toString
The order of how you want the objects to show up in the return string can be reordered depending on how you append them together. Mower can be first or last.
I realized my mistake. My Mower class has tostring() method but does not override the toString() method (difference in syntax).
I have the following class
public class Patient implements Serializable {
private int id;
private String name;
private String desc;
public Patient(int id, String name, String desc) {
this.id = id;
this.name = name;
this.desc=desc;
}
And then the following getter and setter methods in this class.
Declaring the arraylist
ArrayList<Patient> list = new ArrayList<Patient>();
Adding run time data in the list
list.add(new Patient(id++, name.getText(), disDesc.getText())
Now i want the read the elements stored in the list
How can i do that?
System.out.println(list.get(0));
I use this but it returns the object address of the class
You have to override the toString() method of Patient. There, you will return all information on the Patient object that you want to display.
Example: (my personal favorite)
private static final String SEPARATOR = ", ";
#Override
public String toString()
{
StringBuilder builder = new StringBuilder();
builder.append("ID: ").append(id).append(SEPARATOR);
builder.append("Name: ").append(name).append(SEPARATOR);
builder.append("Desc: ").append(desc);
return builder.toString();
}
Example 2:
#Override
public String toString()
{
return "ID: " + id + ", Name: " + name + ", Desc: " + desc;
}
Example 3:
#Override
public String toString()
{
return MessageFormat.format("ID: {0}, Name: {1}, Desc: {2}", id, name, desc);
}
Use either one. It is a matter of preference.
You have to cast the element,
((Patient) list.get(0)).getName();
And you must add a public getter method to your Patient class.
I have a Java Class like this:
public class Employee {
String Name;
int Id;
int Age;
void setName(String tempVal) {
Name = tempVal;
System.out.println(Name);
System.out.println("\n");
}
void setId(int parseInt) {
Id = parseInt;
System.out.println(Id);
System.out.println("\n");
}
void setAge(int parseInt) {
Age = parseInt;
System.out.println(Age);
System.out.println("\n");
}
}
Now I want to parse a employees.xml file using SAXParser using the code in the link: http://totheriver.com/learn/xml/xmltutorial.html#5.2
The problem is when I am adding the tempEmp to the list and accessing the list to print its value in printData() method, the output is something like:
No of Employees '3'.
Employee#140de537
Employee#1c43882a
Employee#15a08be5
Now, how do I extract the name, age and id of the employee individually?
I guess you are adding the Employee object to the list and printing the objects directly from list.If you dont override the toString() method, it will call the toString() method of Object class(superclass of all class), which will be returing the classname#hashcode(hashcode of object).If you want to print some data from your class, you need to override toString() method in your class and return the format you require.
You have to implement a toString() method in the Employee class for it to be displayed correctly, something along these lines:
#Override
public String toString() {
return Id + " " + Name + " " + Age;
}
Also, remember that in Java attribute names should start with a lowercase character, not uppercase.
You want to add some getter methods.
You should also check out the code conventions for Java - some of your variables start with an uppercase letter where they should not.
To get each value individually, you need to add a few get methods
public String getName()
{
return Name;
}
public int getAge()
{
return Age;
}
public int getId()
{
return Id;
}
I have a collection i added CD, DVD, book information into hashsets.
Each one has a keyword and i would like to do a search for a specific keyword and return the specific book,CD,dvd... heres the output to give you an idea..
-Book-
Author: Robert A. Heinlein
# pages 325
title: Starship Troopers
keywords: [science fiction, war, weapons]
-Music-
band: Grateful Dead
# songs: 12
members: [Jerry Garcia, Bill Kreutzman, Keith Godcheaux]
title: Europe In '72
keywords: [acid rock, sixties, jam bands]
-Movie-
director: Sofia Coppola
# scenes: 14
cast: [Bill Murray, Scarlett Johansson]
title: Lost In Translation
keywords: [Japan, loneliness]
>>> items for keyword: science fiction
none
>>> items for keyword: jam bands
none
C:\Java\a03>
I have 3 classes.
Main()
Library - this is where i do all the adding of cd, DVD, books. lookups, etc
Items class(CD class, DVd class, book class) using inheritance..
in main() i am sending in information to the library class to add to the sets.
then i print out all the books, cd, movies just added.
then i do a lookup for a specific keyword.
And this is where i am having problems. i wrote a getkeyword function in CD, DVD, book class.
What i want to do is get the keyword and then see if they match and then return it as a collection.
here is main() i will only show some of it to keep this short - i will not show you how i am adding since it works good..
printItemsForKeyword(out, "science fiction");
printItemsForKeyword(out, "jam bands");
printItemsForKeyword(out, "xxx");
private static void printItemsForKeyword (PrintStream out, String keyword)
{
Collection<Item> items;
out.printf(">>> items for keyword: %s\n\n", keyword);
items = library.itemsForKeyword(keyword);
printItems(out, items);
}
now here in the library class is where i need help
in the itemsForKeyword(String keyword) function...
so, the first thing i am trying to find is "Science Fiction"
I think i need to cast item since item has the CD, DVD, book classes and i need to return a colection???
right now i am trying to return key and it wont since its incompatable with the return.
public class Library
{
private Set<Item> theCDs = new HashSet<Item>();
private Set<Item> theDVDs = new HashSet<Item>();
private Set<Item> theBooks = new HashSet<Item>();
public Collection<Item> itemsForKeyword(String keyword)
{
Item key = new Item();
((CD)key).getKeyword(); // i dont think i am even doing this right
if(key.equals(keyword))
{
return key; // cant return key
}
return null;
}
I did define a getKeywords() function in each of the classes below.
Here is the Items class since you will need to look it over..
import java.io.PrintStream;
import java.util.Collection;
import java.util.*;
class Item
{
private String title;
public String toString()
{
String line1 = "title: " + title + "\n";
return line1;
}
public void print()
{
System.out.println(toString());
}
public Item()
{
}
public Item(String theTitle)
{
title = theTitle;
}
public String getTitle()
{
return title;
}
}
class CD extends Item
{
private String artist;
private String [] members;
private String [] keywords;
private int number;
public CD(String theTitle, String theBand, int Snumber, String... keywords)
{
super(theTitle);
this.artist = theBand;
this.number = Snumber;
this.keywords = keywords;
}
public void addband(String... member)
{
this.members = member;
}
public String getArtist()
{
return artist;
}
public String [] getMembers()
{
return members;
}
public String [] getKeyword()
{
return keywords;
}
public String toString()
{
return "-Music-" + "\n"
+ "band: " + artist + "\n"
+ "# songs: " + number + "\n"
+ "members: " + Arrays.toString(members)
+ "\n" + super.toString()
+ "keywords: " + Arrays.toString(keywords)
+ "\n" + "\n" ;
}
public void print()
{
System.out.println(toString());
}
}
class DVD extends Item
{
private String director;
private String [] cast;
private int scenes;
private String [] keywords;
public DVD(String theTitle, String theDirector, int nScenes, String... keywords)
{
super(theTitle);
this.director = theDirector;
this.scenes = nScenes;
this.keywords = keywords;
}
public void addmoviecast(String... members)
{
this.cast = members;
}
public String [] getCast()
{
return cast;
}
public String getDirector()
{
return director;
}
public String [] getKeyword()
{
return keywords;
}
public String toString()
{
return "-Movie-" + "\n"
+ "director: " + director + "\n"
+ "# scenes: " + scenes + "\n"
+ "cast: " + Arrays.toString(cast) + "\n"
+ super.toString()
+ "keywords: " + Arrays.toString(keywords)
+ "\n" + "\n" ;
}
public void print()
{
System.out.println(toString());
}
}
class Book extends Item
{
private String author;
private int pages;
private String [] keywords;
public Book(String theTitle, String theAuthor, int nPages, String... keywords)
{
super(theTitle);
this.author = theAuthor;
this.pages = nPages;
this.keywords = keywords;
}
public String getAuthor()
{
return author;
}
public String [] getKeyword()
{
return keywords;
}
public void print()
{
System.out.println(toString());
}
public String toString()
{
return "-Book-" + "\n"
+ "Author: " + author + "\n"
+ "# pages " + pages + "\n"
+ super.toString()
+ "keywords: " + Arrays.toString(keywords)
+ "\n" + "\n" ;
}
}
the reason why i think i need to do sometype of cast is because i had to when i added
bandmembers..
public void addBandMembers(Item musicCD, String... members)
{
((CD)musicCD).addband(members);
}
So, what can i do to find a keyword in the items and return those?
would it be better to look directly at the sets and do some type of cast to get it to return? im just stumped..
Thank you..
Create an index (SortedMap<String, List<Item>>) relating keywords to the items they represent. When an object is added to the library, map it to each of its keywords in the index, adding new keywords as needed. Search the index to find the objects.
It's a little hard to follow what you're trying to ask, but I hope the following is what you're after. It looks to me that you're chiefly concerned with getting a Collection of Items, which you want done using the method public Collection<Item> itemsForKeyword(String keyword).
In this method, you should do the following:
Create an empty Collection (either a HashSet or TreeSet depending on whether you need it sorted).
Loop through theCDs. For each Item, get its keywords.
Loop through keywords. If you find one that equals (or equalsIgnoreCase) the one passed in, add the Item to the Collection you created in 1.
Repeat 2 and 3 for theDVDs and theBooks.
Return the Collection you created in 1.
A couple of other things:
I'd suggest that you rename getKeyword to getKeywords, since that's what it's returning.
For the purposes of this method, you would be better off having keywords in a HashSet so that you can do item.getKeyword().containsKey(keyword) instead of the looping in 3. If you do this and need it the method to be case insensitive, you would need to store keywords in all lower case or all upper case, and add in a step 0 to convert the passed in keyword to the correct case before searching. Also, this may not be the way to go if you need to extensively use keywords as an array elsewhere.
Please can anyone tell me what the error is in the following piece of code?
Question is
Create a class person which has
A variable ‘name’ which stores the name of the person.
A constructor that takes a single argument that is used to initialize the name variable
A method getName() which displays the name.
A protected method setName() that takes one argument which is used to modify the name variable.
Create a subclass of the above class called student, which contains
A variable to store PRN of a student
A variable to store course the student belongs to
A method, which displays all the details of the student i.e, name, prn and course.
Program :
class Person
{
String name;
Person(String s)
{
name=s;
}
void getName()
{
System.out.println("Name is "+name);
}
void setName(String sa)
{
name=sa;
}
}
class subPerson extends Person
{
//String sa;
int Prn;
String course;
subPerson(String s,int P,String co)
{
name=s;
Prn=P;
course=co;
}
void displayal()
{
System.out.println("Name is ");
System.out.println("PRN is "+Prn);
System.out.println("course is "+course);
}
}
class Inher
{
public static void main(String args[])
{
int area,volumea;
subPerson h1 = new subPerson("Abhishek",20,"MBA");
h1.displayal();
}
}
Person's constructor takes a String. Since subPerson extends Person, its constructor will invoke a constructor of Person. By default it'll use the no-arg constructor, but since Person doesn't have one, it won't work.
Try changing subPerson's constructor to this:
subPerson(String s,int P,String co)
{
super(s);
Prn=P;
course=co;
}
I assume that compiles (I'm not going to check that), then the fundamental problem is that in the displayal() method, you don't actually print out the name...
System.out.println("Name is ");
should actually be something like
System.out.println("Name is " + name);
Aside from that, there are some problems with not following typcial java coding conventions. While the code may compile and do what is desired, most java guys will likely get hung up on "not following naming conventions" instead of trying to fix the problem because the code looks unusual.
I'd also recommend that you pay more attention to names. They matter a great deal and deserve careful thought.
"subPerson" as a class name leaves me quite cold. Aside from the poor camel case style, the assignment explicitly calls for a class Student. Why did you go with "subPerson"?
I would advise against the "displayal" (sic) method as well. The proper idiom is to override the toString() method in Object.
I'd write it like this:
/**
* Person
* User: Michael
* Date: Sep 27, 2009
* Time: 10:00:00 AM
*/
public class Person
{
private String name;
public static void main(String[] args)
{
Person s = new Student("Foo Bar", "35", "Intro To Java");
System.out.println(s);
}
public Person(String name)
{
if ((name == null) || (name.trim().length() == 0))
throw new IllegalArgumentException("name cannot be blank or null");
this.name = name;
}
public String getName()
{
return name;
}
public void setName(String name)
{
if ((name == null) || (name.trim().length() == 0))
throw new IllegalArgumentException("name cannot be blank or null");
this.name = name;
}
#Override
public String toString()
{
return "Person{" +
"name='" + name + '\'' +
'}';
}
}
class Student extends Person
{
private String prn;
private String course;
Student(String name, String prn, String course)
{
super(name);
this.prn = prn;
this.course = course;
}
#Override
public String toString()
{
return "Student{" +
"name='" + getName() + '\'' +
", prn='" + prn + '\'' +
", course='" + course + '\'' +
'}';
}
}