Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Christopher Mlalazi
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Christopher Mlalazi
Front End Web Development Techdegree Graduate 17,305 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,558 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,305 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.