Modifiers Constructors Constructor OverloadinginJavapdf 2024 08-30-09!58!40
Modifiers Constructors Constructor OverloadinginJavapdf 2024 08-30-09!58!40
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.
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.
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.
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
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.
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.
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 {
int answer = 1, i;
return answer;
// Driver method
}
Study Material by Ms Manmeet Kaur
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
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
class DriverClass {
// Driver method
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
}
Study Material by Ms Manmeet Kaur
class DriverClass {
// Driver method
inst.instanceMethod();
5. 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
//method declaration
int answer = 1, i;
return answer;
// Driver method
}
Study Material by Ms Manmeet Kaur
1. Call-by-value
2. Call-by-reference.
Types of Parameters:
1. Formal Parameter:
Syntax:
// Function body
2. Actual Parameter:
Study Material by Ms Manmeet Kaur
Syntax:
functionName(argument)
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 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.
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);
}
ALGORITHM:
Step 1: Start
Step 4.4: Call the "changeValue" method on "object" and pass "object" as an
argument
Step 5: End
import java.util.*;
// Callee
class CallByReference
{
int a,b;
b=y;
}
// 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);
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.
Syntax:
public className(parameterList)
}
Study Material by Ms Manmeet Kaur
Example
class Dogs
public Dogs()
// No initialization parameters
this.breed = breed;
this.name = name;
this.breed = breed;
{
Study Material by Ms Manmeet Kaur
if (runStatus == 1)
System.out.println("Dog is running");
else
if (tailStatus.equals("Woof"))
else
{
Study Material by Ms Manmeet Kaur
dog1.isRunning(0);
dog2.tailWagging("Woof");
// A dog with both name and breed initialized at the time of object creation.
Output:
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.
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.
class Dogs {
if (runStatus == 1) {
System.out.println("Dog is running");
} else {
if (tailStatus.equals("Woof")) {
} else {
dog1.isRunning(2);
dog2.tailWagging("Woof");
Output:
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
this.name = name;
this.breed = breed;
}
Study Material by Ms Manmeet Kaur
Example,
class Dogs {
public Dogs() {
// No initialization parameters
this.breed = breed;
this.name = name;
this.breed = breed;
if (runStatus == 1) {
System.out.println("Dog is running");
} else {
Study Material by Ms Manmeet Kaur
dog1.isRunning(0);
dog2.tailWagging("Woof");
// A dog with both name and breed initialized at the time of object
creation.
Output:
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