CS F213 Objected Oriented Programming Labsheet 3

Spring 2024

Java Constructors

A constructor initializes an object immediately upon creation. It has the same name as the class in which it resides and is syntactically similar to a method. Once defined, the constructor is automatically called when the object is created before the new operator completes.

Important points about constructors

  1. They have the same name as the class name.

  2. They don't have any return type (see note below).

Note: The implicit return type of a class’ constructor is the class type itself.

Declaring a constructor

class Database {
  Database(){
    System.out.println("Inside Database constructor");
  }
}

class Main {
  public static void main(String args[]) {
    Database newDatabase = new Database();
    System.out.println("Inside Hello class");
  }
}

Output:

Inside Database constructor
Inside Hello class

All classes have constructors by default: if you do not create a class constructor yourself, Java creates one for you. However, then you are not able to set initial values for object attributes. Once you define your own constructor, the default constructor is no longer used.

Parameterized Constructors

Constructors can also take parameters, which are used to initialize attributes.

Declaring a parameterized constructor

class Database {
  String name;
  int age;

  Database(String varName, int varAge){
    name = varName;
    age = varAge;
  }
}

class Main {
  public static void main(String args[]) {
    Database newDatabase = new Database("John", 21);
    System.out.println("Name declared: " + newDatabase.name);
    System.out.println("Age declared: " + newDatabase.age);
  }
}

Output:

Name declared: John
Age declared: 21

this Keyword

Sometimes, a method will need to refer to the object that invoked it. To allow this, Java defines the this keyword. this can be used inside any method to refer to the current object. That is, this is always a reference to the object on which the method was invoked. You can use this anywhere a reference to an object of the current class’ type is permitted.

Example in declaring a constructor:

class Database {
  String name;
  int age;

  Database(String name, int age){
    this.name = name;
    this.age = age;
  }
}

class Main {
  public static void main(String args[]) {
    Database newDatabase = new Database("John", 21);
    System.out.println("Name declared: " + newDatabase.name);
    System.out.println("Age declared: " + newDatabase.age);
  }
}

Output:

Name declared: John
Age declared: 21

Note: This is a way to avoid Instance Variable Hiding

Method Overloading

It is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different (number and/or type of parameters are different). When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading. Return types may be different for different overloaded methods, but, please note that it is not sufficient for only the return type to be different: the parameters must differ for overloaded methods.

class Overloaded{
  void calculate(int a, int b){
    System.out.println(a + b);
  }

  void calculate(int a, int b, int c){
    System.out.println(a * b * c);
  }
}

class Main{
  public static void main(String args[]) {
    Overloaded newOverloaded = new Overloaded();
    newOverloaded.calculate(10, 30);
    newOverloaded.calculate(10, 30, 40);
  }
}

Output:

40
12000

Overloading Constructor:

In addition to overloading normal methods, you can also overload constructor methods. In fact, for most real-world classes that you create, overloaded constructors will be the norm, not the exception

class Area{
  int lenA;
  int lenB;

  //Consider a square
  Area(int singleArg){
    lenA = lenB = singleArg;
  }

  //Consider a rectangle
  Area(int a, int b){
    lenA = a;
    lenB = b;
  }

  void calculateArea(){
    System.out.println(lenA * lenB);
  }

}

class Main{
  public static void main(String args[]) {
    Area square = new Area(10);
    square.calculateArea();

    Area rectangle = new Area(10, 30);
    rectangle.calculateArea();
  }
}

Output:

100
300

Tip: You can also specify a constructor without any arguments by assigning some default values to the variables.

Exercise Problems:

Exercise 1

Declare a class MyQueue with appropriate variables and an array that will store integers. On calling the class, the default constructor behavior would be to initialize all the variables declared in the class and create an array of the size specified by the user input.

Define these methods with the following functionality: enqueue : public method to push an element specified by user input to the back of the queue. dequeue : public method to remove an element from the front of the queue. length: public method to print the current number of elements in the queue. front: public method to print the value of the item in front of the queue without dequeuing (removing) the item. back: public method to print the value of the item in the back of the queue. isEmpty: private method returning a boolean value based on whether the queue is empty or not (use this method in other public methods as required). isFull: private method returning a boolean value based on whether the queue is full or not (use this method in other public methods as required).

Then create a class Main with main() method which will ask the user the max size of the queue and then initialise MyQueue with that size. Then put the following menu options in the while loop, which will keep running until the exit command is explicitly given:

Enter your choice:
1. Enqueue
2. Dequeue
3. Length
4. Front
5. Back
6. Exit

Properly program all the error messages in case of queue is empty or full.

Exercise 2

Declare a class Length with NO constructor explicitly defined. Now define an overloaded method len that will give the length of an array of integers, the length of a string, the length of a single integer (equal to 1), and no argument (equal to 0).

Declare a class Main with main() method where you will give the user the option to find the length of the array, string, a single integer, or nothing as follows:

Choose an option to find the length of:
1. Array of Integers
2. String
3. Single Integer
4. Nothing

Depending upon the option chosen, take further input from the user for array content as:

Enter the length of the array:
3
Enter the elements of the array:
1 2 5

or string:

Enter the string:
Object Oriented Programming

and then return the length from the class Length defined above.

Exercise 3

Consider a class named Book with the following attributes:

title (String): representing the title of the book. author (String): representing the author of the book. pages (int): representing the number of pages in the book.

Implement the Book class with the following constructors:

  1. A default constructor that initializes the title, author, and pages to empty strings and 0, respectively.

  2. A parameterized constructor that takes the title and author as parameters and initializes pages to 0.

  3. Another parameterized constructor that takes all three attributes (title, author, and pages) as parameters (by the same name).

Use this for defining the variables in the constructors.

Define a method details that prints the title, author, pages.

Declare another class Main with main() where you take input from the user and store it in title, author and pages variables, then call all these three constructors and then calling details method to check the details of the book.


Last updated