0% found this document useful (0 votes)
31 views23 pages

Modifiers Constructors Constructor OverloadinginJavapdf 2024 08-30-09!58!40

Uploaded by

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

Modifiers Constructors Constructor OverloadinginJavapdf 2024 08-30-09!58!40

Uploaded by

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

Study Material by Ms Manmeet Kaur

Access Modifiers in Java

Access Modifiers in Java provides a restriction on the scope of the class,


instance variables, methods, and constructors.

There are four Access modifiers in Java- Default, Private, Protected, and Public.
In Java, access modifiers control visibility. private restricts access, like keeping
personal salary details within the family. public allows unrestricted access, akin
to everyone knowing your name. protected is similar to public but with some
limitations. default serves as a baseline, accessible within its package. These
modifiers manage visibility, for instance, variables, constructors, and methods.

Types of Access Modifiers in Java

1. Default Access Modifier

In Java, when class members and methods are not explicitly assigned any access
modifier, they default to having package-private access. This means they can
only be accessed within the same package, hence often referred to as package-
private.

Real-life analogy: Imagine setting your Facebook privacy status to "visible to


your friends only". Similarly, package-private access restricts access to
members and methods to within the same package, akin to only allowing known
friends to view your status.

Understanding package-private access with a Java example:

Access within the same package: Members and methods with default access
can be accessed freely within the same package. Access from another
package: Attempting to access default members from another package results in
an error, as default access doesn't permit this.

2. Private Access Modifier

The private modifier in programming limits access to certain data members and
methods within a class. It's like setting your Facebook status to "only me" - only
you can see it, and similarly, only the class itself can access private members.
Even other classes in the same package can't access them.
Study Material by Ms Manmeet Kaur

3. Protected Access Modifier

Protected access in Java is useful for allowing access within the same package
as well as by subclasses, even if they're in a different package. To access
protected members from another package, you need to extend the class that
contains those members. This means creating a child class in the other package.
Simply creating an object of the class won't grant access to its protected
members; you need to inherit them through a subclass.

4. Public Access Modifier

The public access modifier in Java means there are no restrictions on accessing
the methods, classes, or instance members of a particular class. It allows access
from any package and any class. A real-life example is setting a Facebook status
to "public," allowing anyone on Facebook, whether a friend or not, to see it.
This flexibility makes the public modifier useful for wide accessibility.
Study Material by Ms Manmeet Kaur

Passing arguments

Java Methods

Methods in Java are some blocks of code that perform a specific function. A
method runs only when it is called. A method can accept data as its arguments.
Methods provide for easy modification and code reusability. It will get executed
only when invoked/called. The primary usability of methods is in code reuse:
define the code once and use it many times.

Method Declaration

A method in Java has various attributes like access modifier, return type, name,
parameters, etc.

Methods can be declared using the following syntax:

accessModifier returnType methodName(parameters_list)

//logic of the function

Let us understand what each attribute means -

accessModifier: It defines the method's access type, i.e., from where it can be
accessed in your application.

returnType: It represents the data type of the value returned by the function.
For example, a method in Java declared with int return type should return an
integer value.

methodName: Represents the identifier that can be used to call the method
when required.

parameters: These are the arguments passed into a method necessary for the
function's logic. We can pass data to the methods by specifying them within the
parentheses if the methods have data.
Study Material by Ms Manmeet Kaur

Naming a Method

The naming convention for a method in Java is generally a verb, in mixed case,
with the first letter in lowercase and the first letter of each internal word
capitalized. This naming convention is called the Camel case.

Method Calling
What we saw above is declaring a method. To use the method's functionality,
you need to "call" a method. This is as simple as writing the method's name by
passing its parameters. We should also take note of the function's return type.

Example

class Factorial {

// Declaring method to find factorial of given number n

static int findFactorial(int number) {

// Standard logic to calculate factorial

int answer = 1, i;

for (i = 2; i <= number; i++) answer *= i;

return answer;

// Driver method

public static void main(String[] args) {

//Calling the method findFactorial

int result = findFactorial(7);

System.out.println("Factorial is : " + result);

}
Study Material by Ms Manmeet Kaur

Types of Methods in Java

1. Predefined Method

These are methods that Java class libraries define. They are also called
standard library methods or built-in methods. They can be used by directly
calling them. Some examples include print() in the package
java.io.PrintStream, min() and max() as defined in Math class, etc.

2. User-defined Method

As you might have guessed, a method with custom logic is a user-defined


method. The above example of converting temperature from Celsius to
Fahrenheit is an example of a user-defined method in Java.

How to Call or Invoke a User-defined Method?

To invoke a user-defined method in Java, specify its name and provide any
required arguments. Then, In the main method, call the method using its
name followed by parentheses containing the arguments. Handle the return
value if applicable by storing it in a variable or using it directly.

3. Static Method

A method in a class declared as static does not need an object of the class to
invoke it. All the above built-in methods are static, so you could invoke the
sqrt() method without creating an object of the Math class. In the example of
a user-defined method to convert Celsius to Fahrenheit, the method is also
static

Example,

class StaticMethodDemo {

//method declaration

static void staticMethod() {

System.out.println("This is a static method.");


Study Material by Ms Manmeet Kaur

class DriverClass {

// Driver method

public static void main(String[] args) {

// No need to create an object of the class StaticMethodDemo

StaticMethodDemo.staticMethod();

4. Instance Method

Instance methods in Java are attached to the objects of a class rather than the
class itself. Here, the method belongs to a class whose object must be created
to call the function. This is seen in the code snippet below, where an object
obj of the Demo class is created to call the addNumbers() method.

class InstanceMethodDemo {

//method declaration

public void instanceMethod() {

System.out.println("This is an instance method.");

}
Study Material by Ms Manmeet Kaur

class DriverClass {

// Driver method

public static void main(String[] args) {

// Create object of the class InstanceMethodDemo

InstanceMethodDemo inst = new InstanceMethodDemo();

inst.instanceMethod();

5. Abstract Method

A method without any implementation but only the method signature is


called an abstract method. An abstract method can be declared in an abstract
class or an interface. A regular class can implement an abstract method by
extending the abstract class containing the abstract method.

Abstract methods are used where you need to share the code among closely
related classes or have many standard parameters.Abstract method in an
abstract class.

Example

abstract class Factorial {

//method declaration

public abstract int findFactorial(int n);

class DriverClass extends Factorial {


Study Material by Ms Manmeet Kaur

//Implementing abstract method in abstract class Temperature

//If not implemented, it throws a Compilation error

public int findFactorial(int n) {

int answer = 1, i;

for (i = 2; i <= n; i++) answer *= i;

return answer;

// Driver method

public static void main(String[] args) {

Factorial obj = new DriverClass();

int result = obj.findFactorial(7);

System.out.println("7! is equal to : " + result);

}
Study Material by Ms Manmeet Kaur

Parameter Passing Techniques in Java


Parameter passing in Java refers to the mechanism of transferring data
between methods or functions. Java supports two types of parameters
passing techniques

1. Call-by-value
2. Call-by-reference.

Understanding these techniques is essential for effectively utilizing method


parameters in Java.

Types of Parameters:

1. Formal Parameter:

A variable and its corresponding data type are referred to as formal


parameters when they exist in the definition or prototype of a function or
method. As soon as the function or method is called and it serves as a
placeholder for an argument that will be supplied. The function or method
performs calculations or actions using the formal parameter.

Syntax:

returnType functionName(dataType parameterName)

// Function body

// Use the parameterName within the function

In the above syntax:

 returnType represents the return type of the function.


 functionName represents the name of the function.
 dataType represents the data type of the formal parameter.
 parameterName represents the name of the formal parameter.

2. Actual Parameter:
Study Material by Ms Manmeet Kaur

The value or expression that corresponds to a formal parameter and is


supplied to a function or method during a function or method call is referred
to as an actual parameter is also known as an argument. It offers the real
information or value that the method or function will work with.

Syntax:

functionName(argument)

In the above syntax:

 functionName represents the name of the function or method.


 argument represents the actual value or expression being passed as an
argument to the function or method.

Java supports two types of parameters passing techniques

1. Call-by-Value:

In Call-by-value the copy of the value of the actual parameter is passed to the
formal parameter of the method. Any of the modifications made to the formal
parameter within the method do not affect the actual parameter.

ALGORITHM:

Step 1: Create a class named CallByValueExample.

Step 2: Inside the main method:

Step 2.1: Declare an integer variable num and assign it the value 10.

Step 2.2: Print the value of num before calling the method.

Step 2.3: Call the modifyValue method, passing num as the actual parameter.

Step 2.4: Print the value of num after calling the method

Step 3: Define the modifyValue method that takes an integer parameter value:

Step 3.1: Modify the formal parameter value by assigning it the value 20.

Step 3.2: Print the value of value inside the method.


Study Material by Ms Manmeet Kaur

EXAMPLE - for FileName: CallByValueExample.java

import java.util.*;
public class CallByValueExample
{
public static void main(String[] args)
{
int num = 10;
System.out.println("Before calling method:"+num);
modifyValue(num); // Calling the method and passing the value of 'num'
System.out.println("After calling method:"+num);
}

public static void modifyValue(int value) {

// Modifying the formal parameter


value=20; // Assigning a new value to the formal parameter as value
System.out.println("Inside method:"+value);
}
}
Call-by-Reference:

call by reference" is a method of passing arguments to functions or methods


where the memory address (or reference) of the variable is passed rather than
the value itself. This means that changes made to the formal parameter within
the function affect the actual parameter in the calling environment.

In "call by reference," when a reference to a variable is passed, any


modifications made to the parameter inside the function are transmitted back to
the caller. This is because the formal parameter receives a reference (or pointer)
to the actual data.

ALGORITHM:

Step 1: Start

Step 2: Define the class "CallByReference"


Study Material by Ms Manmeet Kaur

Step 2.1: Declare instance variables: a (int) and b (int)

Step 2.1: Define a constructor to assign values to a and b

Step 3: Define the method "changeValue" inside the "CallByReference" class:

Step 3.1: Accept a parameter of type "CallByReference" called "obj"

Step 3.2: Add 10 to the value of "obj.a"

Step 3.3: Add 20 to the value of "obj.b"

Step 4: Define the class "Main"

Step 4.1: Define the main method

Step 4.2: Create an instance of "CallByReference" called "object" with values


10 and 20

Step 4.3: Print the values of "object.a" and "object.b"

Step 4.4: Call the "changeValue" method on "object" and pass "object" as an
argument

Step 4.5: Print the updated values of "object.a" and "object.b"

Step 5: End

EXAMPLE - for FileName: CallByReferenceExample.java

import java.util.*;

// Callee
class CallByReference
{
int a,b;

// Constructor to assign values to the class variables


CallByReference(int x,int y)
{
a=x;
Study Material by Ms Manmeet Kaur

b=y;
}

// Method to change the values of class variables


void changeValue(CallByReference obj)
{
obj.a+=10;
obj.b+=20;
}
}

// Caller
public class CallByReferenceExample
{
public static void main(String[] args)
{
// Create an instance of CallByReference and assign values using the construct
or
CallByReference object=new CallByReference(10, 20);

System.out.println("Value of a: "+object.a +" & b: " +object.b);

// Call the changeValue method and pass the object as an argument


object.changeValue(object);

// Display the values after calling the method


System.out.println("Value of a:"+object.a+ " & b: "+object.b);
}
}
Study Material by Ms Manmeet Kaur

Constructors in Java

In Java, Constructors initialize the state of an object during the time of object
creation. The constructor in java is called when an object of a class is created.
Constructors must have the same name as the class within which it is defined.

What is Constructor in Java?


A constructor in Java, in the simplest terms, is a specialized method responsible for
initializing an object. It is called at the time of object creation and can be used to
set initial values of an object's data members. Syntax is quite straightforward. It is
the same as how one would define a class but without the class keyword

Syntax:

Following is the syntax for the class:

public class className


{
// Class definition
}

Following is the syntax for its constructor:

public className(parameterList)

// parameterList is a list of values and their types for example:

// type1 data1, type2 data2, ....

// Assign the input parameters to class members

// Perform any other task required

}
Study Material by Ms Manmeet Kaur

Classes are blueprints of objects specifying an object's various fields and


methods. However, constructors in Java are specialized methods that can be
used to assign values to those fields.

Example

class Dogs

private String name;

private String breed;

public Dogs()

// No initialization parameters

public Dogs(String breed)

this.breed = breed;

public Dogs(String name, String breed)

this.name = name;

this.breed = breed;

void isRunning(int runStatus)

{
Study Material by Ms Manmeet Kaur

if (runStatus == 1)

System.out.println("Dog is running");

else

System.out.println("Dog is not running");

void tailWagging(String tailStatus)

if (tailStatus.equals("Woof"))

System.out.println("Dog is wagging its tail");

else

System.out.println("Dog is not wagging its tail");

public class Main

{
Study Material by Ms Manmeet Kaur

public static void main(String[] args)

Dogs dog1 = new Dogs();

Dogs dog2 = new Dogs("Bulldog");

dog1.isRunning(0);

dog2.tailWagging("Woof");

// A dog with both name and breed initialized at the time of object creation.

Dogs dog3 = new Dogs("Snoopy", "German Shepherd");

Output:

Dog is not running

Dog is wagging its tail

Explanation:

“new” is a java keyword that is used to create an instance of the class. dog3 of
type Dogs equals a ‘new’ Dogs with name = "Snoopy" and breed = "German
Shepherd". The dog dog3 is initialized with these parameters.

new Dogs(name, breed) is a call to the constructor. The parameters name and
breed represent the initial state of the new object being created.

Rules for Creating Java Constructor

There are some important and basic rules to create a constructor in


Java.
 Constructor names are always the same as the class name.
 Constructors never have a return type.
Study Material by Ms Manmeet Kaur

 There are four keywords in Java that is NEVER associated with a


constructor – abstract, final, static, and synchronized.
 Constructors in Java are, therefore, also called special methods, which are
invoked automatically at the time of object creation.

Types of Constructor in Java


1. Default Constructor (No-Arg Constructors)

As the name suggests, these constructors do not have any arguments since
they are created by default in Java when the programmer writes no
constructors.

Consider the example of the Dogs class.

class Dogs {

private String name;

private String breed;

void isRunning(int runStatus) {

if (runStatus == 1) {

System.out.println("Dog is running");

} else {

System.out.println("Dog is not running");

void tailWagging(String tailStatus) {


Study Material by Ms Manmeet Kaur

if (tailStatus.equals("Woof")) {

System.out.println("Dog is wagging its tail");

} else {

System.out.println("Dog is not wagging its tail");

public class Main {

public static void main(String[] args) {

Dogs dog1 = new Dogs();

Dogs dog2 = new Dogs();

dog1.isRunning(2);

dog2.tailWagging("Woof");

Output:

Dog is not running

Dog is wagging its tail

Explanation:

In the above code snippet, there are no constructors defined. In such a case,
Java would automatically create a constructor without parameters. Hence, it
Study Material by Ms Manmeet Kaur

is also called the default constructor. It does not initialize any member of the
class. It simply creates the object with no initial state.

2. Parameterized Constructor

In this case, the programmer writes the constructors with one or more
arguments. This allows distinct or same values to be assigned to the object’s
data member during object creation.

Example

public class Dogs {

private String name;

private String breed;

public Dogs(String name, String breed) {

this.name = name;

this.breed = breed;

}
Study Material by Ms Manmeet Kaur

Constructor Overloading in Java


In Java, constructors are similar to methods but without a return type. They
can be overloaded, just like methods, allowing for the creation of multiple
constructors with different parameter lists. Each constructor can serve a
distinct purpose, with the compiler distinguishing them based on the number
and types of parameters they accept. This technique, known as constructor
overloading, enables flexibility in initializing objects based on varying sets
of input parameters.

Example,

class Dogs {

private String name;

private String breed;

public Dogs() {

// No initialization parameters

public Dogs(String breed) {

this.breed = breed;

public Dogs(String name, String breed) {

this.name = name;

this.breed = breed;

void isRunning(int runStatus) {

if (runStatus == 1) {

System.out.println("Dog is running");

} else {
Study Material by Ms Manmeet Kaur

System.out.println("Dog is not running");

public class Main {

public static void main(String[] args) {

Dogs dog1 = new Dogs();

Dogs dog2 = new Dogs("Bulldog");

dog1.isRunning(0);

dog2.tailWagging("Woof");

// A dog with both name and breed initialized at the time of object
creation.

Dogs dog3 = new Dogs("Snoopy", "German Shepherd");

Output:

Dog is not running

Dog is wagging its tail

Now, if one wanted to create an object of type Dogs with the same name or
say with name and breed, they would be able to. They are different in the
number of parameters, and they are the same in that all of them allow for
object creation, although with some differences.
Study Material by Ms Manmeet Kaur

Difference between Constructors and Methods in Java

You might also like