Java: How to use the toString() method of one class in an other one?
You can't cast a Card
object into String
object.
You can get the String
representation of the Card
object through toString()
method.
Try like below
public String toString(int i){
return card[i].toString();
}
How to use the toString method in Java?
From the Object.toString
docs:
Returns a string representation of the
object. In general, thetoString
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.The
toString
method for classObject
returns a string consisting of the
name of the class of which the object
is an instance, the at-sign character
`@', and the unsigned hexadecimal
representation of the hash code of the
object. In other words, this method
returns a string equal to the value
of:
getClass().getName() + '@' + Integer.toHexString(hashCode())
Example:
String[] mystr ={"a","b","c"};
System.out.println("mystr.toString: " + mystr.toString());
output:- mystr.toString: [Ljava.lang.String;@13aaa14a
How to use toString in this example?
There are a couple of issues here.
One, Your question says wheelnumber and mpg should be private.
Second, The datatype should be Integer. Hopefully below solves you question.
public class Vehicle {
//should be private as per question
private Integer wheelnumber;
private Integer mpg;
Vehicle (int wheelnum, int aMpg) {
wheelnumber = wheelnum;
mpg = aMpg;
}
public void display() {
System.out.println("Wheels: " + wheelnumber.toString + " Mpg: " + mpg.toString);
}
}
Now, to elaborate, The method toString() is defined in Java Object class, and any class that you define by default extends it.
The datatype you used - "int" is a primitive data type (taken directly from C - simple but not object oriented approach) which does not extend Java Object class. Thus, you cannot use toString() method with any instance of a primitive datatype.
Whereas "Integer" datatype is a class defined in Java API, it extends Object class and has toString() method defined in it. Thus, you can use toString() method with any instance of this class.
Having said that, if you absolutely have to convert an "int" variable to String, I suggest you do the below:
int i = 10;
System.out.println("Value of i: " + Integer.toString(i));
Note that, int or Integer can easily be converted to string without calling toString() method, as Java kind of automatically does that for you when you concatenate it with a String - something like this:
int p = 10;
Integer q = new Integer(20);
System.out.println("value of p:" + p + ", q:" + q);
But, that is not the conventional way, and I guess not what your teacher wants in this assignment.
How to use the toString method in my runner?
You're almost there! You shoul wrap your code inside runner with some method:
public class BookstoreRunner{
public static void main(String... args) {
Book book1 = new Book("Generic Title", "K", "L", "K Publishing", "Earth",
LocalDateTime.now());
String bookdetails = book1.toString();
System.out.println(bookdetails);
}
}
P.S. Whe you call System.out.println(new Book())
then book.toString()
method is called implicitly and no need to invoke it manually.
P.S.1 Publication
has a problem. author
variable should be initialized before it will be accessed in the constructor:
private final Author author = new Author();
private final Publisher publisher = new Publisher();
public Publication(String title, String firstName, String lastName, String publisherName, String address, LocalDateTime datePublished) {
// ...
}
How to use toString method to print two objects within a third object?
The problem is in your MailingAddress.toString()
function.
You are not using correct object to call toString()
function. Since MailingAddress
is inherited from FullName
so you don't need to create a new member of type FullName
. You should use inherited toString()
of FullName
using super
keyword.
Following is corrected version. See the complete code working here:
public String toString()
{
return super.toString() + " " + streetAddress + "\n" + city + ", " +
province + "\n" + postal;
}
[Note: Relationship between MailingAddress
and FullName
is has-a
and not is a
i.e. MailingAddress
has a FullName
but MailingAddress
is not a FullName
. Above solution is using is-a
relationship. See here the solution using has-a
relationship. ]
How does the toString method display an entire list of objects without iterating a loop?
ArrayList
extends from AbstractList
which extends from AbstractCollection
which overrides the toString
method (defined in Object
)
This then iterates over the list of elements, calling their toString
methods which, in the end, generates the String
public String toString() {
Iterator<E> it = iterator();
if (! it.hasNext())
return "[]";
StringBuilder sb = new StringBuilder();
sb.append('[');
for (;;) {
E e = it.next();
sb.append(e == this ? "(this Collection)" : e);
if (! it.hasNext())
return sb.append(']').toString();
sb.append(',').append(' ');
}
}
How do I easily and neatly print multiple objects using a toString method, that are also aligned?
You can do something like:
public String toString() {
return String.format("|id: %10d |Name: %30s| Age: %02d | Tlf.: %d| Active: %s| Next Payment: %s |", id, getNameTrimmed() , age , tlfNo , activeMember, nextPayment );
}
private String getNameTrimmed(){
if(name.length()>30) {
return name.substring(0,27)+"...";
}
return name;
}
This way the id will have 10 characters (it will still break the format if you have longer IDs)
The name will have 30 so you need to add a method to give you 30 chars name
Using toString() method from child class
The problem lies here, in the Person
and Doctor
class:
@Override
String toString(){
return ...;
}
you are missing the public
specifier. There should be an error / warning about that. Apply it to the method signatures and your code will work as you expect it to.
when to use toString() method
In most languages, toString
or the equivalent method just guarantees that an object can be represented textually.
This is especially useful for logging, debugging, or any other circumstance where you need to be able to render any and every object you encounter as a string.
Objects often implement custom toString
behavior so that the method actually tells you something about the object instance. For example, a Person
class might override it to return "Last name, First name" while a Date
class will show the date formatted according to some default setting (such as the current user interface culture).
Why is it common practice to override the method toString() in java to print the instance variables of the class?
We could. But how will other classes, that know absolutely nothing about your subclasses with your myNewToString method, know how to print a string that textually represents, in a concise but informative way, arbitrary subclasses?
The toString method was designed to be overridden to do that. Yes, it does have default behavior but it's not very useful. Its authors wanted you to override it. Overriding it to return what's commonly practiced is more useful, but you don't have to do that. A toString method for an EmailAddress class can return
public String toString() {
return "EmailAddress{localPart = " + localPart + ", domainName = " + domainName + "}";
}
but it's usually more useful to return something like
public String toString() {
return localPart + "@" + domainName;
}
Related Topics
Why Are Only Final Variables Accessible in Anonymous Class
In Java, How to Determine the Size of an Object
How to Print My Java Object Without Getting "Sometype@2F92E0F4"
What's Wrong With Overridable Method Calls in Constructors
Get Generic Type of Class At Runtime
Calculating the Difference Between Two Java Date Instances
Difference Between Chromedriver and Webdriver in Selenium
How to Use Java.Net.Urlconnection to Fire and Handle Http Requests
Difference Between Public, Protected, Package-Private and Private in Java
Swing Gui Listeners Without Awt
Loop Doesn't See Value Changed by Other Thread Without a Print Statement
Convert a String Representation of a Hex Dump to a Byte Array Using Java
Why Do I Need to Override the Equals and Hashcode Methods in Java
How to Read All Files in a Folder from Java