0% found this document useful (0 votes)
11 views25 pages

Constructors

The document provides an overview of constructors in Java, explaining their purpose in initializing object properties during creation. It details the differences between default and parameterized constructors, as well as the use of the 'this' keyword for referencing instance variables. Additionally, it covers member variables, constructor overloading, and includes examples to illustrate these concepts.

Uploaded by

Pashal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views25 pages

Constructors

The document provides an overview of constructors in Java, explaining their purpose in initializing object properties during creation. It details the differences between default and parameterized constructors, as well as the use of the 'this' keyword for referencing instance variables. Additionally, it covers member variables, constructor overloading, and includes examples to illustrate these concepts.

Uploaded by

Pashal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 25

RUCU

OBJECT ORIENTED
PROGRAMMING I RCS 122

Vincent Pius Bob


Ruaha Catholic University
Department of Computer Science
Faculty of Information and Communication
Technology
JAVA
CONSTRUCTO
RS

Constructors initialize
object properties
upon object creation.
Constructors
A constructor in is a block of code that initializes
(constructs) the state and value during object
creation.
It is called every time an object with the help of a
new () keyword is created. Even if you haven’t
specified any constructor in the code, the Java
compiler calls a default constructor.
Each time a new object is created, at least one
constructor will be invoked.
The main rule of constructors is that they should
have the same name as the class.
Constructors Cont..
A constructor is syntactically similar to a method, but
there are several differences between the two.
 Firstly, a constructor does not have any explicit return
type , not even void.
 Secondly, it is invoked implicitly, whereas a method is
not. i.e., it is automatically called; the constructor is
automatically invoked when an object is created using
the new keyword, relieving you from the need to call it
explicitly.
 Note: It is called constructor because it constructs the
values at the time of object creation. It is not necessary
Constructors Cont..
In Java, programs are often composed of multiple
classes that work together. While a constructor's
primary role is to initialize the state of a single
object within its class, the interaction between
different classes is crucial. One class might create
an instance of another class, passing data through
the constructor to initialize the new object.
Basic Principles of Multiple Classes
Class Definition Rules
Each class can be defined in the same source file
Only one class can have a public modifier which
will contain the main method.
Constructors Cont..
 Consider a program with multiple classes:

package main;
public class Main{
public static void main(String[] args) {
Road.mm("Hello World");
}
}
class Road{
public static void mm(String message){
System.out.println(message);
}
}
Constructors Cont..
 Consider another program with multiple classes:

// Example: MultiClassDemo.java
public class MainClass {
public static void main(String[] args) {
HelperClass helper = new HelperClass();
helper.displayMessage();
}
}
class HelperClass {
void displayMessage() {
System.out.println("Message from HelperClass");
}
Member variables
 Member variables in Java, also known as fields, are
variables declared within a class but outside any method,
constructor, or block.
 They represent the attributes or characteristics of an
object of that class.
 There are two main types of member variables:
 Instance variables: Each object (instance) of a class has
its own copy of instance variables. Changes made to an
instance variable in one object do not affect the value of
the same variable in other objects. Reinitialized in
methods.
 Class variables (static variables): These variables are
Member variables
 Example
public class IntegerClass {
// anInteger is an instance variable.
// Each instance (object) of IntegerClass has its own copy of
anInteger.
int anInteger;

// numberOfObjects is a static variable (or class variable).


// It belongs to the class itself, not to any specific instance.
// There is only one copy of numberOfObjects, shared by all
instances.
static int numberOfObjects = 0;
//methods
Types of Constructors

There are two types of constructors in Java:


Default Constructor (No-arg constructor)
Parameterized Constructor
i. Default Constructor
When a constructor does not have any parameter, is known as
default constructor.
If no constructors are defined in the class, Java provides a default
constructor with no parameters that initializes the object with
default values.
Syntax
class ClassName {
// ClassName() is the default constructor
ClassName() {
// Constructor body (optional initialization statements)
}
// ... other class members (variables, methods)
}
i. Default Constructor cont..

Example
Class Demo{
public Demo () {
System.out.println(“This is Text”);
}
}
i. Default Constructor cont..
class Student {
In this this class,
public void printName(String studentName) {
we are not
System.out.println("Student Name: " + studentName); creating any
} constructor, so
compiler
}
provides us a
public class Rucu {// Main class to demonstrate the Student default
class
public static void main(String[] args) { constructor.
Here, 0 and null
Student myStudent = new Student(); // Create a new Student object named
'myStudent’ and use it to call
values are
provided by
myStudent.printName(“Kajala"); // Pass the name “Kajala" as an argument.
default
Student anotherStudent = new Student(); constructor.
anotherStudent.printName("Alice");
ii. Parameterized Constructors

 Constructors can also take parameters, which is


used to initialize attributes.
 A constructor that has a specific number of
parameters is called a parameterized constructor.
 Unlike default constructors, parameterized
constructors can accept parameters. You can make
the constructor accept any number of parameters.
You can use this type of constructor to assign
different values to objects during creation.
 The parameterized constructor is used to provide
ii. Parameterized Constructors cont..

 Example
public class Main {
int modelYear; //member variable
String modelName; //member variable
public Main(int year, String name) { //constructor
modelYear = year;
modelName = name;
}
public static void main(String[] args) {
Main myCar = new Main(1969, "Mustang");
System.out.println(myCar.modelYear + " " + myCar.modelName);
}
}
ii. Parameterized Constructors cont..

 Example
class Example3 {
private int var; //member variable
public Example3() { //constructor
var = 10;
}
public Example3( int num) {
var = num;
}
public int getValue() {
return var;
}
public static void main (String args[]) {
Example3 obj1 = new Example3();
System.out.println(“Var is:” + obj1.getValue());
Example3 obj2 = new Example3(70);
System.out.println(“Var is:” + obj2.getValue());
this keyword in Java

 In Java, this is a keyword that acts as a reference


to the current object instance within a class. It is
used in instance methods or constructors to
access members (variables, methods,
constructors) of the current object, especially
when there is a naming conflict between instance
variables and local variables or parameters.

Uses of ‘this’
 Distinguishing instance variables from local
parameters: When a method or constructor
this keyword in Java cont..
 Example
class Example {
private int value;
public Example(int value) {
this.value = value; // this.value refers to the instance variable, value
refers to the parameter
}}
 Example 2
Class A{
int a=10;
public void display(){
int a=20;
System.out.println(a);
System.out.println(this.a); //output???
ii. Parameterized Constructors cont..

// Class with member variables


class MyClass {
// Member variables (instance variables)
int myInt;
double myDouble;
String myString;

// Constructor to initialize the member variables


public MyClass(int myInt, double myDouble, String myString) {
// Using 'this' keyword to refer to the instance variables
this.myInt = myInt;
this.myDouble = myDouble;
this.myString = myString;
Quiz
Write a Java program that uses at least two
Constructors.
Constructor Overloading
Constructor overloading allows a class to have
multiple constructors with different parameter lists.
Java determines which constructor to invoke based
on the arguments provided during object creation.

 In Java, constructor overloading allows a class to


have multiple constructors with different
parameter lists for flexible object creation.
Constructor Overloading Example
class Book {
String title;
String author;
// Constructor with one parameter
public Book (String t) {
title = t;
}
// Constructor with two parameters
public Book (String t, String a) {
title = t;
author = a;
}
}
END OF LECTURE SIX
NEXT ON LECTURE
SEVEN

CONTROL STRUCTURES
THANK YOU!

You might also like