Chapter 05 06 [Classes and Objects-2]
Chapter 05 06 [Classes and Objects-2]
Programming in JAVA
ACCESS SPECIFIERS (VISIBILITY MODIFIERS)
Objectives
To distinguish between instance and static variables and methods .
To define private data fields with appropriate, get and set methods .
To encapsulate data fields to make classes easy to maintain
To define the scope and visibility of the data fields and class members in the code
to restrict the levels of access to certain data, ensuring security by preventing
unintended alterations.
Objectives
How to use this reference to Refer to a class’s hidden data fields
How to use this reference to enable a constructor to call another constructor of the
same class
Method overloading ,passing &returning object and garbage collection concepts
Method Abstraction
You can think of the method body as a black box that contains the detailed
implementation for the method.
Optional arguments Optional return
for Input value
Method Header
Black Box
Method body
Access Specifiers (Visibility Modifiers)
To prevent direct modifications of data fields, you should declare the fields (private).
This is known as data field encapsulation.
To provide the client the ability to access and modify private data fields, (set and
get) methods should be written to change and retrieve their values, respectively.
Why data fields should be private? To protect data and to make code easy to
maintain.
Access Specifiers (Visibility Modifiers)
Access Modifiers: are used to set the accessibility (visibility) and specify the
scope of a class, constructor, variable, method, or data member.
There are four types of access modifiers available in Java:
Access Specifiers (Visibility Modifiers)
An access specifier is a Java keyword that indicates how a field or method can be
accessed.
public
• When the public access specifier is applied to a class member, the member can be
accessed by code inside the class or outside.
Private
• When the private access specifier is applied to a class member, the member cannot be
accessed by code outside the class. The member can be accessed only by methods
that are members of the same class.
Access Specifiers (Visibility Modifiers)
If public or private is not used, the specifier consider default.
• When the default access specifier is applied to a class member, The member can be
accessed by any class in the same package (package-private). The default modifier
restricts access to within a package.
Protected
• used with inheritance. (will be discussed later).
Accessor (getters) and Mutator (setters)
Methods
Because of the concept of data hiding, fields in a class are private.
The methods that retrieve the data of fields are called accessors(getters).
The methods that modify the data of fields are called mutators(setters).
Each field that the programmer wishes to be viewed by other classes needs an
accessor.
Each field that the programmer wishes to be modified by other classes needs a
mutator.
Accessors and Mutators
Class name Rectangle
goes here
width : double
Fields are length : double
listed here
+ getters
Accessors + setters
& Mutators
Accessors and Mutators
For the Rectangle example, the accessors and mutators are:
• setLength: Sets the value of the length field.
• public void setLength(double len) …
• setWidth: Sets the value of the width field.
• public void setLength(double w) …
• getLength: Returns the value of the length field.
• public double getLength() …
• getWidth: Returns the value of the width field.
• public double getWidth() …
Other names for these methods are getters and setters.
Setter & getter Methods
In view of the foregoing, private variables can only be accessed within the same
class. However, it is possible to access them if we use public get and set methods.
Getter and Setter are methods used to protect your data and make your code
more secure.
Getter and Setter make the programmer convenient in setting and getting the
value for a particular data type.
The syntax for both is that they start with either get or set, followed by the name of
the variable, with the first letter in an upper-case example: setName() and
getName(), to change and retrieve the value of the name data field, respectively.
Getter method: syntax
The getter method starts with the word “get” followed by the variable name, getter
method returns the value in different data types; int, String, double, float, etc.
Below is an example of the syntax of a getter method:
Write a Java program to create a class called BankAccount with private instance
variables accountNumber and balance. Provide public getter and setter methods to
access and modify these variables.
Exercises
Write a Java program to create a class called Car with the following class members:
• private instance variables company_name , model_name of type String , year, and
mileage of type integer.
• Provide public getter and setter methods to access and modify the variables.
• The value of year can't be greater than current year.
• The model name can't be empty String.
• three different constructors.
Static Method
static method: a method that belongs to a class, not a specific object.
A static method can be invoked without the need for creating an instance of a
class .
Static Method
Static methods (class methods) are not tied to a specific object.
• A static method can be invoked without the need for creating an instance of a class.
• A static method can access static data member and can change the value of it.
• The static method can not use non static data member or call non-static method
directly.
• They are typically used to create utility classes, such as the Math class in the Java
Standard Library.
• this and super cannot be used in static context (explained later).
Static Method
Examples of static methods in java:
• main()
System.out.println()
• All the methods defined in the Math class are static methods ex: Math.sqrt().
public class MyClass {
public static void main(String[] args) {
double num, root;
…
root = Math.sqrt(num);
System.out.println("Root is " + root);
} …
Static Variables, Constants, and Methods
To declare static variables, constants, and methods, use the static modifier.
Static constants are final variables shared by all the instances of the class.
Static variables (class variables) are shared by all the instances of the class.
• The static variable gets memory only once in the class area at the time of class
loading.
• Static data m.embers of class exist even when no object of class type is instantiated
Static Variables
private static int instanceCount = 0;
• The field is initialized to 0 only once, instanceCount field
regardless of the number of times the class (static)
is instantiated.
3
• Primitive static fields are initialized to 0 if no
initialization is performed.
Object1 Object2 Object3
Static Data Field
The static keyword is a non-access modifier used for attributes, which makes their
values the same for all the objects; i.e., when we declare a field static, exactly a
single copy of that field is created and shared among all instances of that class.
The static keyword is mainly used for memory management.
The value of the (static) field can be changed like any other data fields.
Static Data Field
The method that returns the (static) field should be defined as (static) as well.
The method that Modify the (static) field should be defined as (static) as well.
Since the value (static) field is the same for all the objects, you can invoke the (get)
method that returns the value of the (static) field either via an object name or via the
class name itself.
Static Data Field: Explanation
In the above example, we want to make the value of dimension data field is the
same for all the objects. So, as shown in line 6 of a class circle, we add a static
keyword for the dimension data members.
Static Data Field: at object level
Explanation
Remember:
The method that
returns or Modify the
(static) field should
be defined as (static)
as well
Static Data Field: Main
obj1 obj2
S
are
hare
Sh
s
Static variable (dimension):
3
2
3
2
1
The value of (1) is the last value that will be stored
in the memory for the variable (dimension).
Static Data Field: Main
Since the value (static) field is the
same for all the objects, you can
invoke the (get or set) method
that returns or modify the value of
the (static) field either via an
object name or via the class
name itself.
Static Data Field: Main
Output:
Method Overloading
Method overloading: More than one method can have the same name.
Two methods are said to have different formal parameter lists:
• If both methods have a different number of formal parameters.
• If the number of formal parameters is the same in both methods, the data type of the
formal parameters in the order you list must differ in at least one position.
Method Overloading, cont.
public void methodOne(int x)
public void methodTwo(int x, double y)
public void methodThree(double y, int x)
public int methodFour(char ch, int x, double y)
public int methodFive(char ch, int x, String name)
In this case, the parameters of the (Circle) Constructor have the same name as the data fields
(radius, and color). To distinguish between the parameter name (radius, and color) and the data
field (radius, and color), the (this) operator should be used to access the data field.
But if the parameters of the (Circle) Constructor have the same name as the data fields (radius, and
color) and (this) operator is not used, then in this case it will be dealt with (data field (radius, and
color)) as local variable.
The (this) reference:
Enable a constructor to call another constructor of the same class: Example:
The (this) reference:
In the above example, line 14 invokes the constructor with 2 parameters which is in line 8
to set the data fields values as passed from line 14 (i.e., the value of (radius), red)
Passing Objects as Arguments
Objects can be passed to methods as arguments.
Java passes all arguments by value.
When an object is passed as an argument, the value of the reference variable is
passed.
The value of the reference variable is an address or reference to the object in
memory.
A copy of the object is not passed, just a pointer (a reference) to the object.
When a method receives a reference variable as an argument, it is possible for the
method to modify the contents of the object referenced by the variable.
Passing Objects as Arguments
A Rectangle object
length: 12.0
width: 5.0
displayRectangle(box);
Address
balance: 3200.0
address
Before: After:
c1 c1
c2 c2
Output:
(toString) method