Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java

Christopher Mlalazi
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Christopher Mlalazi
Front End Web Development Techdegree Graduate 17,304 Points

public void

Does anyone know why in this code if you look at the declaration for "public Employee" the term "void" not used like in all the other constructors?

 import java.io.*;
public class Employee {

   String name;
   int age;
   String designation;
   double salary;

   // This is the constructor of the class Employee
   public Employee(String name) {
      this.name = name;
   }

   // Assign the age of the Employee  to the variable age.
   public void empAge(int empAge) {
      age = empAge;
   }

   /* Assign the designation to the variable designation.*/
   public void empDesignation(String empDesig) {
      designation = empDesig;
   }

   /* Assign the salary to the variable salary.*/
   public void empSalary(double empSalary) {
      salary = empSalary;
   }

   /* Print the Employee details */
   public void printEmployee() {
      System.out.println("Name:"+ name );
      System.out.println("Age:" + age );
      System.out.println("Designation:" + designation );
      System.out.println("Salary:" + salary);
   }
}

1 Answer

andren
andren
28,520 Points

They are not all constructors. Only public Employee is a constructor, the rest are just regular methods that belong to the class. They have void as their return type due to the fact that they don't return anything.

A constructor never has a return type defined due to the fact that the entire purpose of the constructor is to return an instance of the class itself. It wouldn't make sense to be able to make it return some other data type.

The easiest way of differentiating a constructor from a normal method is that constructors have to be named exactly the same as the class, and have no return type.

If you have any other questions about constructors or methods I'd be happy to answer them.

Christopher Mlalazi
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Christopher Mlalazi
Front End Web Development Techdegree Graduate 17,304 Points

Thanks Andren, am still learning, I just completed the Learn Java track and I am doing some side reading. If I have more questions sure I will ask thanks also.