Please disable adblock to view this page.

← Go home

Beginner Program – Parameterized Constructor (Java)

Java-illustration-reference

April 27, 2016
Published By : Pratik Kataria
Categorised in:

java

public class BankAccount{

	//Data members are called as states of object
	private int accNumber;
	private String accName;
	private int accBalance;

	//Parameterized Constructor
	public BankAccount(int accNumber, String accName, int accBalance){
		this.accNumber = accNumber;
		this.accName = accName;
		this.accBalance = accBalance;
	}

	public void display(){
		//In-built functions usually begin with capital letter (Note 'S' below)
		// + is used for concatenation
		System.out.println("The account number is: " + accNumber);
		System.out.println("The account name is: " + accName);
		System.out.println("The account balance is: " + accBalance);
	}

	
	//Member functions are called behaviours of object
	//boolean is return type of the function below
	public boolean deposit(int amount){	
		if(amount<99){
			return false;		
		}
		
		this.accBalance += amount;

		return true;
	}
	
	public int withdraw(int amt){
		//If you have more than one condition and 
		//those conditions are independent of other conditions
		//use || (or)
		if(amt>accBalance || amt<0){
			return 1;
		}
		
		this.accBalance -= amt;		
		return 0;

	}
	
	//below defines the entry point of your program in java
	public static void main(String [] args){
		
		System.out.println("Hello Java\n");
		
		/* Note:
		 * 1. Memory is allocated on heap.
		 * 2. b1 is a reference of type BankAccount
		 */
		BankAccount b1 = new BankAccount(101, "Pratik", 1000);

		//Member functions can only be called through reference
		b1.display();

	}	
	
}

Java-illustration-reference

Output:

Hello Java

The account number is: 101
The account name is: Pratik
The account balance is: 1000

View Article Page
Download

Pratik Kataria is a budding programmer, web designer and developer.