Java Constructors

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

Java Constructors

In Java, a constructor is a special method that is used to initialize objects of a class. When an
object is created using the new keyword, the constructor of the corresponding class is called
automatically to initialize the object's state.

A constructor has the same name as the class and does not have a return type, not even void. It
can have parameters, which are used to pass values to the object being created. The constructor's
job is to initialize the object's attributes with the values passed in as parameters.

The purpose of constructors in Java is to initialize objects of a class. Constructors are called
when an object of a class is created using the "new" keyword. They have the same name as the
class, and can take parameters or be parameterless. Constructors can be used to set default values
for an object's attributes, or to initialize an object's attributes with values provided by the user. In
general, constructors ensure that an object is in a valid state as soon as it is created, and they can
also be used to perform any necessary initialization or setup for the object.

Here's an example of a constructor for a class named Person:


class Person {
String name;
int age;

public Person(String name, int age) {


this.name = name;
this.age = age;
}
}

In this example, the Person class has two attributes, name and age. The constructor takes in two
arguments, a String for the person's name and an int for the person's age. Inside the constructor,
the this keyword is used to refer to the object being created, and the name and age attributes are
initialized with the values passed in as parameters.

Constructors are often used to set default values for an object's attributes or to perform other
initialization tasks required for the object to be in a valid state. It is possible to define multiple
constructors for a class, each with a different set of parameters, allowing for more flexibility in
how objects are created.

Example 1: A constructor with no parameters


class Person {
String name;
int age;

public Person() {
name = "John Doe";
age = 30;
}
}

In this example, the Person class has a constructor with no parameters. When an object of the
Person class is created using this constructor, the name attribute is set to "John Doe" and the age
attribute is set to 30 by default.
Example 2: A constructor with default values
class Person {
String name;
int age;

public Person(String name) {


this.name = name;
age = 30;
}
}

In this example, the Person class has a constructor with one parameter for the person's name.
When an object of the Person class is created using this constructor, the name attribute is set to
the value passed in as a parameter, and the age attribute is set to 30 by default.

Example 3: A constructor with multiple parameters


class Rectangle {
int width;
int height;

public Rectangle(int width, int height) {


this.width = width;
this.height = height;
}
}

In this example, the Rectangle class has a constructor with two parameters for the width and
height of the rectangle. When an object of the Rectangle class is created using this constructor,
the width and height attributes are set to the values passed in as parameters.

Example 4: A constructor with initialization code


class Employee {
String name;
double salary;

public Employee(String name, double salary) {


this.name = name;
this.salary = salary;
if (salary < 0) {
this.salary = 0;
}
}
}

In this example, the Employee class has a constructor with two parameters for the employee's
name and salary. When an object of the Employee class is created using this constructor, the
name and salary attributes are set to the values passed in as parameters. Additionally, the
constructor contains initialization code that ensures the salary attribute is set to 0 if a negative
value is passed in as a parameter.
Constructors Practice l:
import java.util.Scanner;

class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Brand: ");
String brand = scanner.nextLine();

System.out.print("Storage: ");
int storage = scanner.nextInt();

System.out.print("Price: ");
double price = scanner.nextDouble();

Phone phone = new Phone(brand, storage, price);

System.out.printf("\n%s has a memory of %d GB and a


price of Php%.0f!\n", phone.brand, phone.storage, phone.price);
}
}

class Phone {
String brand;
int storage;
double price;

public Phone(String brand, int storage, double price) {


this.brand = brand;
this.storage = storage;
this.price = price;
}
}

Explanation:
This is a Java program that allows a user to input the brand, storage, and price of a phone and
then creates an object of the class Phone using the provided input values.

The Scanner class is used to get the user input for the phone's brand, storage, and price, which
are then used to create a new Phone object. The Phone class has three instance variables: brand,
storage, and price, which are initialized through the constructor.

The constructor takes three parameters: brand, storage, and price and assigns them to their
respective instance variables using the this keyword.

Finally, the program prints the details of the Phone object using the printf() method. The %s
placeholder is used to display the brand value, %d is used to display the storage value, and %.0f
is used to display the price value without any decimal places.
Constructors Practice 2:
import java.util.Scanner;

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Published: ");
String publisher = scanner.nextLine();

System.out.print("Year Published: ");


int yearPublished = scanner.nextInt();

System.out.print("Price: ");
double price = scanner.nextDouble();
scanner.nextLine(); // consume the remaining newline
character

System.out.print("Book Title: ");


String title = scanner.nextLine();

Book book = new Book(publisher, yearPublished, price,


title);
book.displayBookDetails();
}
}

class Book {
private String publisher;
private int yearPublished;
private double price;
private String title;

public Book(String publisher, int yearPublished, double


price, String title) {
this.publisher = publisher;
this.yearPublished = yearPublished;
this.price = price;
this.title = title;
}

public void displayBookDetails() {


System.out.printf("\n%s is published by %s on %d. It
sells at the price of Php%.2f.\n",
title, publisher, yearPublished, price);
}
}

Explanation:
This Java code creates a class called "Book" that has attributes of Publisher, Year Published,
Price, and Title. It also has a constructor that initializes the attributes with the values passed to it.

In the main method, the code asks the user for the inputs for the attributes of the Book object
using a Scanner object. After receiving the inputs, it creates a Book object using the constructor
and passes the user inputs. Finally, it calls the displayBookDetails() method to print the details
of the Book object.
The displayBookDetails() method uses printf() method to print the formatted string with the
values of the Book object's attributes. The method prints the title of the book, publisher, year
published, and price.

You might also like