You are on page 1of 59

{ }

Creating and Calling


Constructors with
Parameters
In Java, a constructor is a block of codes similar to the method. It is called when an
instance of the class is created. At the time of calling constructor, memory for the object is
allocated in the memory.
It is a special type of method which is used to initialize the object.

Every time an object is created using the new() keyword, at least one constructor is called.

It calls a default constructor if there is no constructor available in the class. In such case,
Java compiler provides a default constructor by default.

Rules for creating Java constructor

• Constructor name must be the same as its class name


• A Constructor must have no explicit return type
• A Java constructor cannot be abstract, static, final, and
synchronized
Types of Java constructors
There are two types of constructors in Java:
• Default constructor (no-arg constructor)
• Parameterized constructor
Java Default Constructor
A constructor is called "Default Constructor" when it doesn't have any parameter.
Java Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized constructor.

The parameterized constructor is used to provide different values to distinct objects. However, you can
provide the same values also.
A constructor is a special method that is called when
an object of a class is created.

Constructors have the same name as the class and do


not have a return type, not even void.

They are called automatically when an object of the


class is created using the new keyword.
Whenever we use new keyword to create an instance of a class,
The constructor is invoked and the object of the class is returned.

Since constructor can only return the object to class, it’s implicitly
done by java runtime and we are not supposed to add a return type
to it.

If we add a return type to a constructor, then it will become a


method of the class. This is the way java runtime distinguish
between a normal method and a constructor.
Creating constructor

Creating constructor with parameters


Constructors can also take parameters, which is used to
initialize attributes.
Calling a Constructor:
You call constructors using the new keyword followed by the
constructor invocation.
“this” Reference
In Java, the this keyword is a reference to the current object within a
method or constructor. When used within a constructor, this refers
to the object being constructed. Understanding how to use this in
constructors is essential for managing object initialization and
resolving potential naming conflicts between instance variables and
parameters or local variables.

Purpose of this in Constructors:


Disambiguation: When a constructor's parameter names conflict with
instance variable names, using this helps distinguish between the
two.
Disambiguation:
Consider a class Person with instance variables name and age. Let's
say you have a constructor that takes parameters with the same
names:
In this scenario, both assignments inside the constructor are
ambiguous because the parameter names shadow the instance
variable names. To resolve this, you can use this to refer to the
instance variables explicitly:
Using Static Field
In the world of Java programming, static fields play a significant role in
defining class-level variables that are shared across all instances of a class.

Static fields are declared using the static keyword and are associated with
the class itself rather than with any specific instance of the class. They are
commonly used to store data that is shared among all objects of a class,
such as configuration settings, counters, or constant values.

Since static fields are not tied to any specific instance, they can be accessed
using the class name itself, without the need for object instantiation.
When it comes to initializing static fields, Java offers a few different approaches. Let's discuss
each of them in detail:
Initialization at the Point of Declaration:
The simplest way to initialize a static field is to provide an initial value directly at the point of
declaration. For example:
Static Initialization Blocks:
Sometimes, initializing a static field requires more complex logic or
multiple statements. In such cases, we can use static initialization
blocks, denoted by the static keyword followed by a block of code
enclosed in curly braces.

The code inside the block is executed when the class is loaded, after the
initializations at the point of declaration.
Initialization Using Static Methods:
Another approach to initializing static fields is by using static methods. These
methods can be called explicitly or within a static block to perform initialization
tasks. By encapsulating the initialization logic in a static method, you can improve
code readability and separate concerns.
It's important to note that the order of static field initialization
follows the order of their appearance in the code. If one static
field relies on another static field, make sure the dependent field
is initialized before the dependent one.

Furthermore, it's worth mentioning that static field initialization


occurs only once, regardless of how many instances of the class
are created. Therefore, any modification to a static field by one
instance will affect all other instances of the class.
Compositions
and
Nested Classes

Presented By: Alijiah Mae V. Alburo


Composition
WHAT IS A COMPOSITION?

• Composition is the process of making one


class a data member of another class
• A type of relationship or association in Java
used to reuse a code and reduce duplicity
from one class to another.
• The composition in OOP is used to describe
a specific type of "Has a" relationship.
Benefits and Features of
Composition in Java
• Code Reusability: You can reuse the same Engine class • Testability: Easier to test individual components
in other classes like Motorcycle or Boat. (classes) in isolation.

• Flexibility: You can easily change the type of the • A composition-based design has a lesser number
contained object at runtime. of classes.

• Encapsulation: You control how the contained object is


accessed and used.
HAS-A RELATIONSHIP
COMPOSITION IN JAVA
A composition in Java between two objects associated with each
other exists when there is a strong relationship between one class
and another. Other classes cannot exist without the owner or
parent class. For example, A ‘Human’ class is a composition of
Heart and lungs. When the human object dies, nobody parts exist.

How It Works:
• 1. Define a class (the whole) with an instance variable of the
type of the other class (the part).
• 2. Create the contained object and assign it to the instance
variable in the constructor or other methods of the whole
class.
• 3. The whole class can interact with the contained object
through its methods.
EXAMPLE:
LET'S CONSIDER A CAR CLASS THAT has-a Engine class:
Nested Classes
in Java
In Java, nested classes
are a way to define
classes inside other
classes. They provide a
mechanism to group
related functionality
together and improve
code organization.
More about
Nested Classes

• Java nested class is a class which is declared inside the class or interface.

• We use inner classes to logically group classes and interfaces in one place so that it can
be more readable and maintainable.

• Additionally, it can access all the members of outer class including private data members
and methods. (non-static)
TYPES OF NESTED
CLASSES
There are the types of nested classes, the non-static,
local, anonymous, and static nested classes.

• NON-STATIC NESTED • STATIC NESTED CLASS


CLASS (INNER CLASS):

• LOCAL INNER CLASS • ANONYMOUS INNER CLASS


Non-static Member Class (Inner Class):
• DEFINITION: A CLASS DEFIN ED W ITHIN AN OTHER CLASS, BU T N OT MARKED W ITH
THE STATIC KEYWORD.
• Access: Can access all members (inclu d i ng private) of the outer class through
the OuterClass.t his reference .
• Lifetime: Tied to an inst ance of the outer cla ss. An inner cla ss inst a nce ca nnot
exist without an outer class inst a nce .
Static Nested Class :
• DEFINITION: A class defined within another class and marked with the st atic
keyword.
• Access: Can only access st atic memb ers of the outer class. Cannot access non -st atic
members (including private) of the outer class.
• Lifetime: Exists independent of any outer class inst ance.
Local Inner Class:
• A C LASS DEFINED INSIDE A BLO C K O F C O DE , U SUALLY WIT H IN A METH OD BODY, AN
INITIALIZ ATION BLOC K, A FOR LO O P, O R E V E N AN IF STAT E ME N T.
• Not a member of the encl os i ng cl a s s . It exi sts s ol el y wi thi n the s cope of the bl ock where
i t' s defi ned.
KEYPOIN TS:
• NO AC C ESS MODIFIERS: LOC AL IN N E R C LASSE S C AN N O T B E DE C LARED AS PU BLIC , PRIVATE,
OR PRO T E C T ED.
• AC C ESS: C AN AC C ESS LOC AL VARIABLES OF T H E ENC LOSING MET H OD IF DEC LARED AS FINAL .
C AN NOT AC C ESS TH E OU TER C LASS ME MB E RS DIRE C T LY.
Anonymous Inner Classes:
• DEFINITION: A CLASS DECLARED AN D IN STAN TIATED AT THE SAME TIME, W ITHOU T A
SEPARATE N AME. OFTEN USED W ITH IN TERFACES OR ABSTRACT CLASSES.
• Access: Similar to local classes, cannot access outer class members directly.
• Benefits: Concise way to implemen t inter fa ces or shor t pieces of functio na l it y.
Do you have
any questions?
Automaticlly
Imported, Prewritten
Constants
In Java, there are some
constants that are
automatically imported or
prewritten in certain classes or
interfaces. These constants
provide commonly used values
or references that are
frequently used in Java
programming. Here are some
examples:
Java.lang Package

The java.lang package is automatically imported


in every Java class, so you can directly use its
constants without explicit import statements.
Examples of commonly used
constants in java.lang include:
Integer.MAX_VALUE: The maximum value an int can have.

Integer.MIN_VALUE: The minimum value an int can have.

Math.PI: The value of Pi (π) constant.

Math.E: The value of Euler's number constant.

You might also like