Constructor java

Constructor is a block of code of another class.The main purpose of it is to instantiate an object of the other class.In general it’s possible to programm any code in one class, but it’s not really efficient way of programming.If your block of code is very big you, you will lose overview of your project.

Syntax:

Default constructor

Classname variable = new Classname();

Constructor with overloaded parameters

Classname variable = new Classname(Attribute1,Atttribute2 …);

If you don’t define a  Constructor, the compiler creates  automatically a default constructor without parameters.

How to create a constuctor with overloaded parameter?

Classname{

….

Classname(String name,String name2){

this.name = name;

this.name2 = name2;

}}

Example:

public class Customer {
private String firstName; // access modifier is private only inside the class its possible to access
private String LastName;
public static int ID = 12; // static is like reference the value can be changed outside the class
// example:you can change or ask for the value in the other class with System.out.println(Customer.ID (getter))
// or set the value >> Customer.ID = 16;
Customer(String firstName,String LastName){ //Contructor
	this.firstName = firstName;
	this.LastName = LastName;
	
}
public String getName() { // 
	return this.firstName; // the keyword "this" is a reference call 
}
public void setName(String name) { 
// Method with 1 overloaded String
this.firstName = name ;

}

public String getLastName() { 
	return this.LastName;
}
public void setLastName(String name) {
this.LastName = name ;

}

}

public class Main { // class name 

	public static void main(String[] args) { // main Method with 1 overloaded parameter

		
		Customer c1 = new Customer("Alex","Mueller"); // initialize a constructor
		
		Customer.ID = Customer.ID + 1; // static access of the variable ID
		System.out.println(c1.getName()); // output of public Method
		System.out.println(c1.getLastName()); //  output of public Method
		System.out.println(Customer.ID); // ouput of static variable ID

	}
	
	

}

Leave a Reply

Your email address will not be published. Required fields are marked *