Chapter Two
Objects and Classes
Outline
• Defining a class • Access Modifiers
• Creating an Object • Encapsulation
– Instantiating and using • Constructors
objects
– Printing to the Console
– Methods and Messages
– Parameter Passing
– Comparing and Identifying
Objects
– Destroying Objects
Defining a Class
– A class is a template/blue print/ design that describes the
behaviors/states that object of its type support.
– A class can have any number of methods to access the value of
various kinds of methods.
– Class definition consists
• Instance /class variable as a data members
• Methods as member functions (Actuator and mutator)
– You could have several class definition in a program
Defining a Class
public class Dog{ This class has 3 methods and 3
String breed; instance variables.
int age Methods like:- barking(), hungry(),
String color; sleeping()
States like:- breed, age, color.
void barking(){
//body .....
}
void hungry(){
//body ....
}
void sleeping(){
//body .....
}
Creating Objects
• A class provides the blueprints for objects.
• So basically an object is created from a class/instance of a class.
• In java, the new keyword is used to create new objects.
There are three steps when creating an object from a class
1. Declaration- a variable declaration with a variable name of an
object type
2. Instantiation- the ‘new’ key word is used to create the object.
3. Initialization- the ‘new’ key word is followed by a call to a
constructor. This call initializes the new object.
Example on creating object
public class Puppy
{
public Puppy(String name){
// This constructor has one parameter, name
System.out.println("Passed name is: " + name);
}
public static void main(String[] args) {
// The following statement will create an object
Puppy myPuppy = new Puppy("Tommy");
}
}
Instantiating and using objects
• Instance variables and methods are accessed via
created objects.
• To access an instance variable the fully qualified path
/* First
should be . create an object */
ObjectReference = new Constructor();
/* Now call a variable as follows */
ObjectReference.variableName;
/* Now you can call a class method as follows
*/
ObjectReference.methodName();
public class Dog { Accessing instance
int dogAge;
variables, methods
public Dog(String name){
// This constructor has one parameter, name.
System.out.println("Name chosen is: " + name);
}
public void setAge(int age){
dogAge = age;
}
public int getAge(){
System.out.println("Dog's age is: " + dogAge);
return dogAge;
}
public static void main(String[] args) {
/* Object creation */
Dog myDog = new Dog("Tommy");
/* Call class method to set dog's age */
myDog.setAge(2);
/* Call another class method to get dog's age */
myDog.getAge();
/* You can access instance variable as follows */
System.out.println("Variable value: " +
myDog.dogAge);
}
Variable Types
A class can contain any of the following variable types
Local variable
Instance variable
Class variable
Local Variables
Local variables are declared in methods,
constructors, or blocks.
Local variables are created when the method,
constructor or block is entered and the variable will be
destroyed once it exits the method, constructor or
block.
Access modifiers cannot be used for local variables.
Local variables are visible only within the declared
scope.
There is no default value for local variables so local
variables should be declared and an initial value should
be assigned before the first use.
Local Variable example
public class LocalVariable{
public void tellMyBatch(){
int batchYear = 2011;
int year = 2;
System.out.println("Your batch: " + batchYear + " year: " +
year);
}
public static void main(String[] args) {
LocalVariable lv = new LocalVariable();
lv.tellMyBatch();
}
}
Instance variables:
Instance variables are declared in a class, but outside of any method,
constructor or any block.
Instance variables are created when an object is created with the
use of the keyword 'new' and destroyed when the object is destroyed.
Instance variables hold values that must be referenced by more than one
method, constructor or block, or essential parts of an object's state that
must be present throughout the class.
Instance variables can be declared in class level before or after use.
Access modifiers can be given for instance variables.
Conn… Instance Variable
Instance variables are visible for all methods, constructors and block in
the class.
Instance variables have default values. For numbers the default value is 0, for
Booleans it is false and for object references it is null.
Values can be assigned during the declaration or within the constructor.
Instance variables can be accessed directly by calling the variable name
inside the class.
However within static methods and different class (when instance
variables are given accessibility) should be called using the fully qualified
name. ObjectReference.VariableName.
public class Employee { Instance Variable
// This instance variable is visible to all classes
public String name; example
// Salary variable is visible only in Employee class
private double salary;
// The name variable is assigned a value in the
constructor.
public Employee(String empName){
name = empName;
}
// The salary variable is assigned a value
public void setSalary(double empSal){
salary = empSal;
}
// This method prints employee detail
public void printEmp(){
System.out.println("Name: " + name);
System.out.println("Salay: " + salary);
}
public static void main(String[] args) {
Employee empOne = new Employee("Daniel");
empOne.setSalary(10000.0);
empOne.printEmp();
}
Class/static variables:
Class variables known as static variables are declared with
the static keyword in a class, but outside of any method, constructor or
any block.
There would only be one copy of each class variable per
class, regardless of how many objects are created from it.
Static variables are rarely used other than being declared as
constants. Constants are variables that are declared as
public/private, final and static.
Constant variables never change from their initial value.
Class/Static variables cont.
Static variables are created when the program starts and destroyed
when the program stops.
Visibility is similar to instance variables.
Default values are same as instance variables.
Static variables can be accessed by calling with the class name.
ClassName.VariableName
When declaring class variables as public static final, then variables
names (constants) are all in upper case.
Instance variable: It will be different from object to object and
object's property while static variable is Class's property .
3. Class Variable example
public class Circle { Circle.java
public static float pi = 3.14159265f;
public float area(float r){
return pi * r * r;
}
}
public class CircleTest { CircleTest.java
public static void main(String[]
args) {
Circle c = new Circle();
float area = c.area(3.0f);
System.out.println("Area = " +
area);
Example: Class/static variables
class Employee{
// Salary variable is a private static variable
private static double salary;
// DEPARTMENT is a constant variable
public static final String DEPARTMENT = "Development ";
public static void main(String[] args) {
salary = 1000.0;
System.out.println(DEPARTMENT + "average salary: " +
salary);
}
}
Comparing and identifying objects
• In Java, there are two ways to compare objects:
== compares object references to see if they point to the
same object in memory
.equals() compares the content of objects to see if they are
logically equivalent.
• For example, consider two String objects:
String str1 = "Hello";
String str2 = new
String("Hello");
cont.
• In this example, str1 and str2 contain the same content,
but they are not the same object. To check for logical
equality, you would use .equals():
if (str1.equals(str2)) {
System.out.println("The strings are equal");
}
• To check for reference equality, you would use ==:
if (str1 == str2) {
System.out.println("The strings have the same
reference");
}
Destroying Objects
• In Java, objects are automatically destroyed by the
garbage collector when they are no longer referenced by
any part of the program. However, you can explicitly
destroy an object by setting its reference to null.
MyObject obj = new MyObject();
// use obj
obj = null; // destroys the object
• It's important to note that setting an object reference to
null does not immediately destroy the object. The garbage
collector will eventually destroy the object when it
determines that it is no longer needed.
Modifiers
Modifiers are keywords used to specify the accessibility of class
members such as fields, methods and, some, to the class itself.
Modifiers are prefixes that you add to those definitions to change
their meanings.
There are two types of modifiers
• Access modifiers - are used to control the visibility of classes, interfaces,
variables, constructors, and methods. In Java, there are four types of access
modifiers: private, default, protected, and public.
• Non Access Modifiers - are used to modify the behaviour of classes,
variables, methods, and constructors. Some of the commonly used non-access
modifiers in Java include static, final, abstract, synchronized, and volatile.
Access Control Modifiers
• Java provides a number of access modifiers to set access levels
for classes, variables, methods and constructors.
• The four access levels are:
Default access: This access level is also known as "package-
private". If no access modifier is specified, the member or class is
accessible only within its own package.
Private access: Members or classes declared as "private" can only
be accessed within the same class.
Public access: Members or classes declared as "public" can be
accessed from anywhere, including outside of the package and
from subclasses.
Protected access: Members or classes declared as "protected" can
be accessed within the same package and from subclasses, even if
they are in a different package.
Non Access Modifiers:
• Java provides a number of non-access modifiers to achieve
many other functionality.
The static modifier for creating class methods and
variables
The final modifier for finalizing the implementations of
classes, methods, and variables.
The abstract modifier for creating abstract classes and
methods.
Public
Any method or variable is visible to the class in which it is defined,
but what if you want to make method/variable visible to all the
classes outside this class?
The answer is obvious: simply declare the method or variable with
public access.
A variable or method with public access has the widest possible
visibility. Anyone can see it. Anyone can use it.
Public modifier example
public class MyClass {
public int myPublicVariable; // public variable
public void myPublicMethod() { // public method
// Code here
}
}
Package-private
It has no precise/specific name
Default access | Package access | package-private
No access modifier specified in a declaration.
it will be possible to say package explicitly, but for now
it is simply the default protection when nothing has
been specified as a name.
Package-private cont.
Why was package made a default?
When you’re designing a large system and you partition your
classes into work groups to implement smaller pieces of that
system, the classes often need to share a lot more with one
another than with the outside world.
The need for this level of sharing is common enough that it
was made the default level of protection.
Default access modifier -package
public class MyClass {
int packagePrivateVar; // package-private variable
void packagePrivateMethod() { // package-private method
System.out.println("This is a package-private
method");
}
}
public class MainClass {
public static void main(String[] args) {
MyClass myObj = new MyClass();
// Accessing package-private variable
myObj.packagePrivateVar = 10;
System.out.println("Package-private var value: " +
myObj.packagePrivateVar);
// Accessing package-private method
myObj.packagePrivateMethod();
}
Protected
– The protected access modifier is one of the four access
modifiers used to control the visibility and accessibility of
classes, methods, and variables within a program.
– The protected access modifier provides a level of access that
is more restrictive than public but less restrictive than private
or package-private (default).
Protected cont.
– These subclasses are much closer to a parent class than
to any other “outside” classes for the following reasons:
• Subclasses are usually more intimately aware of the internals
of a parent class
• Subclasses are often written by you or by someone to whom
you’ve given your source code.
• Subclasses frequently need to modify or enhance the
representation of the data within a parent class.
Protected class
– Even though AnyClassInTheSamePackage is in the
same package as AProtectedClass, it is not a subclass
of it (it’s a subclass of Object).
– Only subclasses are allowed to see, and use,
protected variables and methods.
Private
– Private is the most narrowly visible, highest
level of protection that you can get.
– It is the diametric opposite of public. private
methods and variables cannot be seen by any
class other than the one in which they are
defined .
– Any private data, internal state, or
representations unique to your implementation
anything that shouldn’t be directly shared with
subclasses is private.
– Remember that an object’s primary job is to encapsulate its data
to hide it from the world’s sight and limit its manipulation.
– The best way to do that is to make as much data as private as possible
Access Modifies cont.
– By convention, unless an instance
variable is constant , it should
almost certainly be private.
Access Modifiers Summary
Outside
Access Same Same package by Outside
Modifier Class Package subclass only Package
public Yes Yes Yes Yes
protected Yes Yes Yes No
default Yes Yes No No
private Yes No No No
Encapsulation
• Refers to the bundling of data and methods into a single unit, and
controlling access to that unit to prevent unwanted modifications or access
by other parts of the program.
• Encapsulation helps to ensure the integrity of an object's data by
making it private and only allowing access through public methods.
• This approach ensures that the object's state can only be modified in
a controlled and consistent manner, which can help prevent errors
and improve the reliability of the code.
• To achieve encapsulation, we typically use private access modifiers to
restrict access to an object's fields (data) and provide public
accessors (getters) and mutators (setters) to allow controlled access to
Benefits of Encapsulation
• Data hiding: Encapsulation hides the data of a class from other classes.
This prevents other classes from accessing the data directly, which can
help to protect the data from being modified or corrupted.
• Data integrity: Encapsulation can help to ensure the integrity of data by
preventing other classes from modifying the data directly. This is because
the class's public methods can be used to control how the data is modified.
– Data integrity, refers to the accuracy, consistency, and reliability of
data over its entire lifecycle. It ensures that data remains unaltered,
complete, and trustworthy, regardless of accidental or intentional
changes, corruption, or unauthorized access.
public class Employee {
private String name; Encapsulation
private double salary;
example
public Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
public String getName() {
return name;
}
public String setName(String n) {
this.name = name;
}
public void setSalary(double salary) {
if (salary >= 0.0) {
this.salary = salary;
}
}
public double getSalary() {
return salary;
}
}
Accessor(get) Mutator(set) Methods
– If instance variables are private, how do you give access to
them to the outside world?
– The answer is to write “accessor” and “mutator” methods:
Accessor(get) Mutator(set) Methods
cont.
– A class’s private fields can be manipulated only by its methods.
– Classes often provide public methods to allow clients of the class to
set (i.e., assign values to) or get (i.e., obtain the values of)
private instance variables.
– Set methods are also commonly called mutator methods,
because they typically change an object’s state. i.e., modify the
values of instance variables.
– Get methods are also commonly called accessor methods or
query methods.
See PoorDog.java & PoorDogTestDrive.java
class Student { Application with
private String ID; private String fName;
two classes
private String lName;
private String gender;
private int age;
public void setId(String idn){ID= idn;}
public void setFirstName(String fname){fName =
fname;}
public void setLastName(String lname){ lName =
lname;}
public void setAge(int a){age = a;}
public void setGender(String sex){gender = sex;}
public String getfName() {return fName;}
public String getId() {return ID;}
public String getlName() {return lName;}
import java.util.Scanner;
public class TestStudent
{
public static void main(String []arg)
{
Student s1 = new Student();
Scanner input = new Scanner(System.in);
System.out.print("ID:");
s1.setId(input.next());
System.out.print("FName:");
s1.setFirstName(input.next());
System.out.print("LName:");
s1.setLastName(input.next());
System.out.print("Age:");
s1.setAge(input.nextInt());
System.out.print("Sex:");
s1.setGender(input.next());
System.out.println("ID\tFName\tLname\tAge\tSex");
System.out.println(s1.getId()+"\t"+s1.getfName()+"\t"+ s1.getlName()+"\t"+s1.getAge()+"\t"+
s1.getGender());
}
Constructors
A constructor is used to initialize an object of a class
when the object is created.
In fact, Java requires a constructor call for every object
that’s created.
The Keyword ‘new’ requests memory from the
system to store an object, then calls the corresponding
class’s constructor to initialize the object.
The call is indicated by the parentheses after the class
Constructors cont.
– By default, the compiler provides a default constructor with
no parameters in any class that does not explicitly include a
constructor.
– When a class has only the default constructor, its instance
variables are initialized to their default values.
• The default values for the primitive data types in Java are as
follows:
• byte, short, int, long: 0
• float, double: 0.0
• boolean: false
• char: '\u0000' (the null character)
• For object references, the default value is null. This means that if
a variable of a reference type is declared but not explicitly
Uses of Constructors
Prints the string
• For initializing instance variables. representation of the
hiObj reference variable,
public class Hi{ which is the address in
String name; memory where the object
is stored
public Hi(){
this.name = "CoSc 2044 class\n";
}
public static void main(String[] args)
{
Hi hiObj = new Hi();
System.out.println(hiObj);
}
}
Rules of using Constructors
Constructors have the same name as the class name.
Constructors have access modifiers(package, private,
protected, public)
Constructors do not have return types.
Constructors can be invoked only during object
creation or from other constructors using this keyword.
Types of Constructors
There are three types of constructors:
Default Constructors
No-argument Constructors
Parameterized Constructors
Default Constructors
If you do not implement any constructor in your class , Java compiler
inserts a default constructor into your code on your behalf.
By default, the compiler provides a default constructor with no
parameters in any class that does not explicitly include a constructor.
When a class has only the default constructor, its instance
variables are initialized to their default values.
Compiler creates
default constructor
• If you declare any constructor for a class, the Java
compiler will not create a default constructor for that
class.
• The body of default constructor is empty.
No-argument Constructor
Constructor with no arguments is known as no-arg
constructor.
The signature is same as default constructor, how ever the
body can have any code.
Parameterized Constructors
• Constructor with arguments (or Parameters) is
known as Parameterized constructor.
• Constructors gets invoked after creating objects.
public class Student { Parametrized Constructors
int age;
String name; example
double cgpa;
public Student(int sage, String sname, double scgpa){
age = sage;
name = sname;
cgpa = scgpa;
}
public void info(){
System.out.println("Age:" + age + " Name:" + name + " CGPA:" +
cgpa);
}
public static void main(String[] args) {
Student s1 = new Student(19, "yared", 3.56);
s1.info();
}
Constructor Overloading
• It is possible to have more than one constructors in one program.
• Constructor overloading is a concept of having more than one constructor
with different parameters list.
public class Demo{
Constructor without
Demo(){
Argument
//…….
}
Demo(String s){
Constructor with
//……..
String Argument
}
Demo(int i){
//…….
Constructor with int
}
Argument
}
Quiz
• Create a Java class called "Person" with the following
properties:
– A private string variable called "name" to store the person's
name
– A private integer variable called "age" to store the person's age
• The class should also have the following methods:
– A public constructor that takes two arguments: a string for the
person's name and an integer for the person's age. The
constructor should initialize the name and age properties.
– Public getters and setters for both the name and age properties.
• In the main method of a separate class, create an instance
of the Person class and prompt the user to enter a name
and age for the person. Use the setters to set the name