zam
how to use toString method?
1 Answer(s)      5 years and 5 months ago
Posted in : Java Beginners
i'm a new student, and learn with java.

How to create a class named Employee with name and salary. Make a class Manager inherit from Employee with an instance field named department. Supply a method toString() that prints the manager?s name, department and salary. Make another class named Director which inherits from Manager that has an instance field named carAllowanceAmount. Supply the toString() method for Director that prints all of its instance variables. Also, write a program name TestQ3 that instantiates an object of each of these classes and invokes the toString() method of each of these object.
(Note: all instance variables must be assigned with private accessibility and methods with public accessibility)

how to create the program?

help me please...
Advertisement
View Answers

January 30, 2010 at 2:44 PM


Hi Friend,

Try the following code:

/*class Person{
int year;
String name;
public Person(String name,int year){
this.year=year;
this.name=name;
}
public String toString() {
return "Name= " + name + ", Year= " +year;
}
}
class Student extends Person{
private String degree;
public Student(String name,int year,String degree){
super(name,year);
this.degree=degree;
}
public String toString() {
super.toString();
return "Name= "+super.name+", Year= "+super.year+", Degree= " +degree;
}

}
class Lecturer extends Person{
private int salary;
public Lecturer(String name,int year,int salary){
super(name,year);
this.salary=salary;
}
public String toString() {
return "Name= "+super.name+ ", Year= "+super.year+ ", Salary= " +salary;
}
}
public class TestQ2
{
public static void main(String[] args)
{
Person p = new Person("Angel", 1959);
Student s = new Student("Ane", 1979, "MCA");
Lecturer e = new Lecturer("Aurther", 1969, 65000);
System.out.println(p);
System.out.println(s);
System.out.println(e);

}
}*/
class Employee{
int salary;
String name;
public Employee(String n,int sal){
this.name=n;
this.salary=sal;
}
public String toString() {
return "Name= " + name + ", Salary= " +salary;
}
}
class Manager extends Employee{
private String department;
public Manager(String name,int salary,String dept){
super(name,salary);
this.department=dept;
}
public String toString() {
super.toString();
return "Name= "+super.name+", Salary= "+super.salary+", Degree= " +department;
}

}
class Director extends Employee{
private int carAllowanceAmount;
public Director(String name,int salary,int amount){
super(name,salary);
this.carAllowanceAmount=amount;
}
public String toString() {
return "Name= "+super.name+ ", Salary= "+super.salary+ ", Car Allowance Amount= " +carAllowanceAmount;
}
}
public class TestQ2
{
public static void main(String[] args)
{
Employee p = new Employee("Angel", 20000);
Manager s = new Manager("Ane", 30000, "Computer");
Director e = new Director("Aurther", 40000, 5000);
System.out.println(p);
System.out.println(s);
System.out.println(e);
}
}

Thanks