Konstruktoret
Konstruktori eshte nje metode qe ben te mundur inicializimin e objektit, duke i vendosur vlere fushave te tij.
Metoda konstruktor ka te njejtin emer me klasen .
Konstruktoret mund te marrin argumenta ose jo.
Nje klase mund te kete disa konstruktore te mbingarkuar.
Zakonisht konstruktori krijohet ne fillim te klases, perpara se te ndertohen metodat e tjera.
Shembull i ndertimit te nje konstruktori:
Punonjes()
{
emri = "Alda";
rroga = 200;
kodi = 15;
}
Deklarimi i objektit:
Punonjes p = new Punonjes(); i jep objektit p vlerat e siperme duke mbivendosur vlerat default.
Shembull i konstruktorit me argumenta:
Punonjes(String e, double r, int k)
{
emri = e;
rroga = r;
kodi = k;
}
Deklarimi i objektit:
Punonjes p = new Punonjes("Genci",200,8);
Perdorimi i klasave si tipe te dhenash
Kur deklarojme objekte te klasave tona ne java, perdorim te njejten menyre si kur deklarojme variabla te tipeve primitive si psh:
int a;
Pra ne fillim tipi e me pas emri i objektit.
Pra klasat mund te perdoren si tipe te dhenash te cilat i kemi krijuar vete me perpara.
Shembull i perdorimit te klasave si tipe te dhenash.
Employee.java
public class Employee
{
private int empNum;
private String empLastName;
private String empFirstName;
private double empSalary;
public int getEmpNum()
{
return empNum;
}
public void setEmpNum(int emp)
{
empNum = emp;
}
public String getEmpLastName()
{
return empLastName;
}
public void setEmpLastName(String name)
{
empLastName = name;
}
public String getEmpFirstName()
{
return empFirstName;
}
public void setEmpFirstName(String name)
{
empFirstName = name;
}
public double getEmpSalary()
{
return empSalary;
}
public void setEmpSalary(double sal)
{
empSalary = sal;
}
}
MethodsThatUseAnEmployee.java
import java.util.Scanner;
class MethodsThatUseAnEmployee
{
public static void main (String args[])
{
Employee myEmployee;
myEmployee = getEmployeeData();
displayEmployee(myEmployee);
}
public static Employee getEmployeeData()
{
Employee tempEmp = new Employee();
int id;
double sal;
Scanner input = new Scanner(System.in);
System.out.print("Enter employee ID ");
id = input.nextInt();
tempEmp.setEmpNum(id);
System.out.print("Enter employee salary ");
sal = input.nextDouble();
tempEmp.setEmpSalary(sal);
return tempEmp;
}
public static void displayEmployee(Employee anEmp)
{
System.out.println("\nEmployee #" + anEmp.getEmpNum() +
" Salary is " + anEmp.getEmpSalary());
}
}