Transcript L4

OOP IV
toString method
If you have a toString method defined in your class, this method will
automatically be called whenever you stick your class inside a print or
println statement.
class object
{
int ID = 15;
String name = “Hello”;
}
void main()
{
object ob1 = new object();
System.out.println(ob1);
}
output:
random nonsense
class object
{
int ID = 15;
String name = “Hello”;
public String toString()
{
Print(name + “ “ + ID);
}
}
void main()
{
object ob1 = new object();
System.out.println(ob1);
}
output:
Hello 15
Exercise 1
Create a class called Cars with the following data:
•
•
•
•
String model
int year
double gasMileage
String style
Create a constructor that will ask for values to all four and assign
values. Create a toString method that will output all the values.
In void main, declare an instance of this class and use a println()
statement to output the object.
Object inside of an object? YES!!!!!
class Honda
{
// code not shown
}
class cars
{
private Honda Accord = new Honda();
}
class human
{
final int ARMS = 2;
final int LEGS = 2;
private String name;
private int age;
int method1()
{
// code not shown
return value;
}
}
class mammal
{
human h1 = new human();
int x = h1.method1();
void method1()
{
// code not shown
}
}
Exercise 2
Create a class called array1. This class will have an integer array of size
10. Its constructor is to set the values of this array to random values
between 0-100. Create a toString method for this class so we can print
out the arrays as necessary.
Now create a class called array2. This class will declare 5 instances of
class array1. Now create a method called smallest. This method will
determine which of the 5 instances of the classes has the smallest sum
and print out the values.
Exercise 3
Create a class called Cars. Cars is to have three variables:
• int numDoors[ ]
• String company[ ]
• String models[ ]
Assume the arrays to be 5 long per.
Now create a class called owners. Owners will declare an instance of class
Cars. It will also have a variable named
String owner[ ] // also 5 long
Its constructor will go through the array five times and ask for input to all
fields. Display your results, toString method may help you here.