Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to print the data values of an object?

I have created a class employee in Java, where each object of the class stands for a staff. The objects take 3 parameters – Name, Dept. and Salary. The program looks like this:

public class employee
{
    String name;
    int salary;
    String dept;
    employee staff1 = new employee("x","IT",100000);
    employee staff2 = new employee("y", "HR", 200000);
    public employee(String n, String d, int s)
    {
        this.name= n;
        this.salary= s;
        this.dept = d;
    }   
    public static void main (String args [])
    {
        
    }
    public void Display()
    {
            
    
        
        
    }
}

I want to make a method (the Display method in the code) which takes the object name as a parameter (the code does not have a parameter) and returns (or prints) its data values. Please also tell me what should come in the main method. Thanks in advance.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

first of all try to study the programming basics, it’s an embarrassing question

public class Employee {

private String name;
private int salary;
private String dept;

public employee() {

}

public employee(String n, String d, int s) {
    this.name= n;
    this.salary= s;
    this.dept = d;
}   

public static void main (String args[]) {
    Employee staff1 = new Employee("x", "IT", 100000);
    staff1.display();

    Employee staff2 = new Employee("y", "HR", 200000);  
    staff2.display();
}

public void display() {              
    System.out.println(this);
}

public String toString() {
  return "Name: " + name + ", Salary: " + salary + ", Department: " + dept;
}

}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading