0% found this document useful (0 votes)
9 views48 pages

4 - Classes and Objects

The document provides an overview of classes and objects in object-oriented programming, defining a class as a blueprint for creating objects and explaining the concept of encapsulation. It discusses access modifiers (public, private, default, protected) that control visibility and access to class members, as well as the importance of using getters and setters for data protection. Additionally, it covers constructors for initializing objects and emphasizes the significance of encapsulation in maintaining data integrity.

Uploaded by

raphaelvicuna
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)
9 views48 pages

4 - Classes and Objects

The document provides an overview of classes and objects in object-oriented programming, defining a class as a blueprint for creating objects and explaining the concept of encapsulation. It discusses access modifiers (public, private, default, protected) that control visibility and access to class members, as well as the importance of using getters and setters for data protection. Additionally, it covers constructors for initializing objects and emphasizes the significance of encapsulation in maintaining data integrity.

Uploaded by

raphaelvicuna
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/ 48

Any immediate questions

before our session?

Please raise your


hand if you have J

Image source: https://www.kindpng.com/imgv/oRomoh_raised-hands-png-transparent-hand-emoji-png-download/


Classes and Objects

CCPROG3 – AY2223T3 – ETighe


Outline
• Formally defining a class and an object
• Access modifiers
• Class-level
• Property-/method-level
• Encapsulation
• Constructors
What is a Class?
• A class is a structure that defines the data and the
methods to work on that data
• It serves as a blueprint for an object
• It has properties (attributes) and methods (behaviors)
What is an Object?
• An object or instance is an executable copy of a class
• There can be any number of objects of a given class, in
memory, at any one time
• Objects have a copy of the properties and methods of
the class it was instantiated from
Classes and Objects

INSTANTIATION

OWL CLASS OWL OBJECTS

Owl owl1 = new Owl("red");


Owl owl2 = new Owl("blue");
Creates a new instance
It was mentioned before that
it’s easier to model scenarios
in OOP…
For example, let’s take a look
at the following
environment…
What objects exist
within this
environment?
• Subreddit
• Post
• Comment
• User
• Awards

Most of the above


are entities of the
environment, but
there are also UI
objects, like
buttons
Let’s focus on a Post

What characteristics
does a post have?
• Title
• Text/caption
• Image/Video
• Spoiler tag
• Post id
• Time stamp
• Etc.

Some characteristics
are requirements, while
others are optional (can
be null).
Hypothetically, what
action/methods might a
have post?
• getTitle() : String
• Gain access to
the title for
displaying on
screen
• isSpoiler() : Boolean
• If true, blur post;
otherwise, no blur
• setText(String text) :
void
• Useful for editing
the post’s text
We’ve already been creating
classes, but let’s first
formalize some of the ideas
we’ve been working with
Declaring a Class
• When declaring a class in Java, these components are written
in order
1. The class access modifier
2. The keyword abstract or final, if declaring an abstract or final
class
3. The keyword class followed by the class name, with the initial
letter capitalized by convention
4. The keyword extends followed by the parent class name, if any
5. The keyword implements followed by a comma-separated list of
interfaces implemented by the class, if any
6. The class body, surrounded by braces { }
For now, we’ll focus on #s 1, 3, and 6
Declaring a Class #s 2, 4, and 5 will be discussed in time

• When declaring a class in Java, these components are written


in order
1. The class access modifier
2. The keyword abstract or final, if declaring an abstract or final
class
3. The keyword class followed by the class name, with the initial
letter capitalized by convention
4. The keyword extends followed by the parent class name, if any
5. The keyword implements followed by a comma-separated list of
interfaces implemented by the class, if any
6. The class body, surrounded by braces { }
Class Access Modifiers
• There are three you’ll need to keep in mind
• Public
• Private
• Default (err… no access modifier)
Class Access Modifiers – Public
• The public class access IF ClassA IS PUBLIC...
modifier allows the class to
PACKAGE 1 PACKAGE 2
be accessed by any other
class ClassA ClassASub

• If ClassA is public, all the ClassB ClassD

other classes can access it.


All classes can access it
This includes classes from
other packages (folders) On Packages, think of these are directories that help
organize your code
java.util.Scanner à Scanner is a class that’s part of
the java.util package
Class Access Modifiers – Private
• The private class access IF ClassA IS PRIVATE...
modifier doesn’t allow the
PACKAGE 1 PACKAGE 2
class to be accessed by
any other class ClassA ClassASub

ClassB ClassD

No classes can access it


Class Access Modifiers – Default
• The default class access IF ClassA HAS NO MODIFIER...
modifier is used whenever no
access modifier is specified PACKAGE 1 PACKAGE 2

• This modifier is also called ClassA ClassASub

package-private
ClassB ClassD
• Not all OOP languages support
default All classes in Package 2 can’t access it.
This includes the subclass
Class Access Modifiers
• There are three you’ll need to keep in mind
• Public
• A class declared with the public modifier is visible to all classes
of any package
• Private
• A class can’t be declared private, unless it’s an inner class. If so,
only its outer class can access it
• Default (err… no access modifier)
• A class with no modifier is only visible within its own package.
Even subclasses from another package can’t access it
While we’re talking about
access modifiers, note that
all properties and methods
have access modifiers
Property and Method Access Modifiers
• There are four you’ll need to keep in mind
• Public
• Private
• Protected
• Default (no access modifier)
Class Access Modifiers – Private
• Methods or variables A PRIVATE METHOD OR
PROPERTY IN ClassA...
declared as private are only
PACKAGE 1 PACKAGE 2
accessible within the class
they are declared in ClassA ClassASub

• Even classes of the same ClassB ClassD

package will not be able to


Can’t be accessed by any class
access these members other than ClassA itself
Class Access Modifiers – Protected
• Methods or variables A PROTECTED METHOD OR
PROPERTY IN ClassA...
declared as protected are
PACKAGE 1 PACKAGE 2
accessible by subclasses
within any package ClassA ClassASub

• Classes can’t be declared ClassB ClassD

protected. This access


Can be accessed by subclasses
modifier is generally used in from any package
a parent-child relationship
We’ll discuss more of this when we enter inheritance J
Class Access Modifiers – Public
• Methods or variables A PUBLIC METHOD OR
PROPERTY IN ClassA...
declared as public are
PACKAGE 1 PACKAGE 2
accessible from everywhere
in the program ClassA ClassASub

• The public access modifier ClassB ClassD

has the widest scope


Can be accessed by any class
among all other access from any package
modifiers
Class Access Modifiers – Default
• The default access modifier A METHOD OR PROPERTY WITH
NO ACCESS MODIFIER...
is used whenever no
PACKAGE 1 PACKAGE 2
access modifier is specified
• Methods or properties ClassA ClassASub

having a default access ClassB ClassD

modifier are accessible only


Can be accessed by any class from
within the same package Package 1, but not from other
packages.
(package-private) Even subclasses from other packages
do not have access to them
Questions so far?
Property and Method Access Modifiers
• There are four you’ll need to keep in mind
• Public
• accessible by any class from any package
• Private
• Only accessible within the class they’re declared in
• Protected
• Only accessible by subclasses from any package
• Default (no access modifier)
• Only accessible to classes from their package
Assuming these files are in the same package

public class Tweet { public class Controller {


private int tweetId; private int tweetId;
public String caption; public String caption;

public void setTweetId(int i) { public static void main(String[] args) {


this.tweetId = i; Tweet tweet = new Tweet();
} tweet.tweetId = 193325834;
} }
}

Is this allowed?
No. tweetId is private to
the Tweet class.
BTW, in case you’re wondering…

public class Tweet {


The keyword "this" refers to the
private int tweetId;
public String caption;
instantiated object. So one might:
As an example… Access variables – this.varName
public void setTweetId(int i) { Call methods – this.methodName
this.tweetId = i;
} This convention is useful when you have
vs
conflicting variables in the same scope.
public void setTweetId(int tweetId) {
this.tweetId = tweetId;
}
In the 2nd method is syntactically correct

}
Assuming these files are in the same package

public class Tweet { public class Controller {


private int tweetId; private int tweetId;
public String caption; public String caption;

public void setTweetId(int i) { public static void main(String[] args) {


this.tweetId = i; Tweet tweet = new Tweet();
} tweet.setTweetId(193325834);
} }
}

Is this allowed?
Yes as setTweetId is public.
Assuming these files are in the same package

public class Tweet { public class Controller {


private int tweetId; private int tweetId;
public String caption; public String caption;

public void setTweetId(int i) { public static void main(String[] args) {


this.tweetId = i; Tweet tweet = new Tweet();
} tweet.caption = "Hello world";
} }
}

Is this allowed?
Yes… but this is discouraged. We
usually want to avoid allowing others to
modify an objects properties directly.
Encapsulation
• Is one of the four OOP Principles
• Objects are the most important • Other objects must not be able to
units in an OOP system and must read or edit data stored in other
maintain their integrity objects directly
• Individual objects are responsible • These must be done through
for managing (i.e. storing, access points, normally in the
updating and returning) their own form of getter and setter
object data. methods.
Encapsulation: Good Practice
• In most cases, properties/variables should be kept
private to a class
• To edit or retrieve properties, getter/setter methods
should be used
• Getter/setter methods give the class control over how data
is shown or edited by other entities
• Getters -> getVarName(); returns the variable
• Setters -> setVarName(Var var); usually no return value
Note: For those using IDEs, there’s usually a way to generate your
getters and setter
Encapsulation: Good Practice
• Note that you don’t have to create getters and setters
for all a class’s variables
• General rule of thumb: Allow the class to protect its
own data
public class Tweet {
private Location location;

public void setLocation(Location l) throws IllegalArgumentException {


if(l == null) {
In this example, you
throw new IllegalArgumentException();
might want to require
else {
that a Tweet always
this.location = l;
}
have a location (i.e.
} Location is non-null).
public class Controller {
This way, your Tweet
private int tweetId;
public String caption;
protects itself –
showing the
public static void main(String[] args) { importance of
Tweet tweet = new Tweet(); encapsulation.
tweet.setLocation(null);
}
}
Constructors
• When we create our objects, it makes sense to assign
values upon creation – not create then set
• Hence, we can utilize Constructors or special methods
that are only called during instantiation
Writing a Constructor
public class Person {
Has to match
public Person() {

No return type
(not even void)
Writing a Constructor
public class Person {
private String name;
private int age;

public Person() {

}
Writing a Constructor
public class Person {
private String name;
private int age;

public Person(String name, int age) {


this.name = name;
this.age = age;

}
Constructor Usage
public class Person { This is a
private String name; syntax error
private int age;

public Person(String name, int age) {


this.name = name;
this.age = age; public class Controller {
public static void main(String[] args) {
}
Person j = new Person();
j.setName("Juan");
}
j.setAge(17);

Person m = new Person();


m.setName("Mario");
m.setAge(18);

}
}
Constructor Usage
public class Person {
private String name;
private int age;
This now adheres to the
public Person(String name, int age) { class’s constructor
this.name = name;
this.age = age; public class Controller {
public static void main(String[] args) {
}
Person j = new Person("Juan", 17);
Person m = new Person("Mario", 18);
}
}
}
Multiple Constructors
public class Person {
private String name;
private int age;

public Person() {
Sets default
this.name = "No name";
values on this.age = 0;
creation
}

Requires the public Person(String name) {


name this.name = name;
variable this.age = 0;
}

Requires the public Person(String name, int age) {


both this.name = name;
variables this.age = age;
}
}
No Constructor…
If this is written…
public class Person {
private String name;
private int age;
}

Then the constructor is blank and


requires no parameters.

It would look something like…


public class Person {
private String name;
private int age;

public Person() {

}
}
Questions? J
Summary
• A class is a template, while an object is an instance
• There are access modifiers at the class-level and the
property-/method-level
• Public
• Private
• Default
• Protected (for property-/method-level only)
• Encapsulation advocates for protecting a class’s data
Summary
• Getters and setters help with enforcing encapsulation
• Constructors help in initializing an object
Reading Assignment
• Kindly read up on Unified Modeling Language or UML
• We’ll discuss more of this next meeting and have an
exercise as well J

• Btw, there are two practice exercises available for the


previous module in case you’re looking to practice with
more with Java
-fin-

You might also like