Uploaded by Jhon Rhey Valleramos

L1

advertisement
DCIT 50: Object Oriented Programming
Introduction to ObjectOriented Programming
CLASSES AND OBJECTS IN JAVA
Russel L. Villacarlos
Simple Poll Program
•Consider a simple program for creating a poll/survey
• This app wil be referred to as SimPoll for the rest of the lecture
•A poll will have one question and at least 2 choices
• New choices can be added while the poll is active
• Adding a new choice will cast one vote to it
•For simplicity, the poll will end after a specified number of votes have
been casted
• This limit is specified before the poll starts
• When ties occur when the poll ends, they will be broken arbitrarily
SimPoll – Ver 1.0
•An excerpt of a simple
implementation is given on the right
(see the full code from our Github
repository)
public class SimPoll{
public static void main(String[] args) {
String question = "";
String choices[] = new String[2];
int votes[] = new int[2];
int choices_count = 0;
int current_votes = 0;
int max_votes;
Scanner in = new Scanner(System.in);
System.out.println(“Question:");
question = in.nextLine().trim();
•The code include variables like
question, options[], votes[],
etc. to store all the information
System.out.println(“Choices: (min. 2)");
String choice;
while(true){
/* Code for adding options */
}
System.out.println("Maximum votes:");
max_votes = in.nextInt();
•The code is quite messy and has
repeated process e.g., adding a new
option
while(current_votes < max_votes){
/* Code for voting or add option */
}
/* Code to output result */
}
}
SimPoll – Ver 2.0
public class SimPoll{
static String question = "";
static String choices[] = new String[2];
static int votes[] = new int[2];
static int choices_count = 0;
static int current_votes = 0;
static int max_votes;
•A function is a set of code grouped
together to perform a specific task
public static void main(String[] args) {
setUpPoll();
startPoll();
showPollResult();
}
private static void setUpPoll(){
/* Code to configure the poll */
}
private static void startPoll(){
/* Code for voting or adding options */
}
private static void showPollResult(){
/* Code to output the result*/
}
private static boolean addChoice(String choice){
/* Code to add choice to choices[] */
}
• It has a name and can have an input
and output
• Use a function by calling its name in
the code (with the given input if
required)
•Idea: Separate the parts of the
program into functions to reduce
complexity
• setUpPoll() for creating the poll,
• addChoice() for adding new choice
to the poll
• etc.
}
SimPoll – Ver 2.0
public class SimPoll{
static String question = "";
static String choices[] = new String[2];
static int votes[] = new int[2];
static int choices_count = 0;
static int current_votes = 0;
static int max_votes;
•Functions are created once and
can be used many times
public static void main(String[] args) {
setUpPoll();
startPoll();
showPollResult();
}
private static void setUpPoll(){
/* Code to configure the poll */
}
private static void startPoll(){
/* Code for voting or adding options */
}
private static void showPollResult(){
/* Code to output the result*/
}
private static boolean addChoice(String choice){
/* Code to add choice to choices[] */
}
• addChoice() can be called
inside setUpPoll()and
startPoll()
•Functions makes your code
manageable
• Easily identify the step being
performed at a given area in
your program
• Localized changing of code
and testing/debugging
}
SimPoll – Ver 3.0
public class Poll {
String question = "";
String choices[] = new String[2];
int votes[] = new int[2];
int choicesCount = 0;
int currentVotes = 0;
int maxVotes;
int lead = -1;
• The code for the app can be grouped as:
public String getQuestion() {
return this.question;
}
public void setQuestion(String question) {
this.question = question;
}
public String[] getChoices() {
// Output the array of choices
}
public boolean addChoice(String newChoice){
// Store more choice
}
public boolean hasChoice(String choice){
// Check if the input is a choice
}
public boolean vote(String choice){
// Add a vote to the given choice
}
• User interface (UI) – input and output thru the
command line
• Poll manipulation – variables to store poll
related values and manipulate them
•Idea: Separate all poll manipulation code
from the UI and move them to a separate
Poll class
• The Poll class will be stored in its own file
•Think of a class as a self-contained unit of
code that contains variables and functions for
manipulating this variables
/* More function follows */
}
public class SimPoll{
public static void main(String[] args) {
Poll poll = new Poll();
setUpPoll(poll);
startPoll(poll);
showPollResult(poll);
}
SimPoll – Ver 3.0
private static void setUpPoll(Poll poll) {
Scanner in = new Scanner(System.in);
System.out.print("Poll question:");
String question = in.nextLine().trim();
poll.setQuestion(question);
•To use the Poll class in the SimPoll
app, we need to create an actual poll
instance: Poll poll = new Poll()
System.out.println("Choices: (min. 2)");
String newChoice;
while(true){
System.out.print("New Choice: ");
newChoice = in.nextLine().trim();
if(newChoice.isBlank()){
if(poll.isReady()){
break;
}
}else{
poll.addChoice(newChoice);
}
}
• The variable poll stores the created
poll instance
• The code new Poll() creates the new
instance
• The Poll class becomes a new data
type
•The instance of a class is called an
object
}
}
System.out.printf("Maximum votes:");
poll.setMaxVotes(in.nextInt());
in.nextLine();
/* Additional code follows */
public class SimPoll{
public static void main(String[] args) {
Poll poll = new Poll();
setUpPoll(poll);
startPoll(poll);
showPollResult(poll);
}
SimPoll – Ver 3.0
private static void setUpPoll(Poll poll) {
Scanner in = new Scanner(System.in);
System.out.print("Poll question:");
String question = in.nextLine().trim();
poll.setQuestion(question);
•Manipulating the poll object is done
using the functions declared in the class
• Ex: poll.setQuestion(question) sets
the question of the given poll object
• Ex: poll.addChoice(newChoice) adds
the new choice to the list of choices of the
poll object
• The way the function is called via the
object is dot notation
System.out.println("Choices: (min. 2)");
String newChoice;
while(true){
System.out.print("New Choice: ");
newChoice = in.nextLine().trim();
if(newChoice.isBlank()){
if(poll.isReady()){
break;
}
}else{
poll.addChoice(newChoice);
}
}
•The code that uses an object from a class
is referred to as the client of the class
• The SimPoll app is the client of the Poll
class
}
}
System.out.printf("Maximum votes:");
poll.setMaxVotes(in.nextInt());
in.nextLine();
/* Additional code follows */
Class and Objects
•A class is like a blueprint of an entity in a program and is composed
of attributes and methods
•Attributes (properties or state or instance variables) are the
variables for storing the data needed by the entity
• Ex: From the Poll class we have question, choices[], votes[], etc.
•Methods are the functions for interacting with the entity to
manipulate its attributes
• Ex: From the Poll class we have getQuestion(), setQuestion(),
addChoice(), etc.
Class and Objects
•An object is an instance of the entity created from the blueprint
(class)
• The new keyword is used to construct an object from a class
• Ex: new Poll()
•Multiple distinct objects can be created from a single class
• Ex: Poll poll1 = new Poll(), poll2 = new Poll() creates two distinct
Poll objects that can be manipulated separately
• poll1.setQuestion(question1) changes the question of poll1 but not
poll2
Visual representation of int a = 10:
References
10
•The code Poll poll = new Poll()
contains two distinct things:
• The reference variable poll
• The object created via new Poll()
a
Visual representation of Poll poll = new
Poll():
question
•Reference variable is a special kind of
variable that holds (the address in memory)
of an object
• Contrast it with primitive variables – variables
whose type are int, float, char, etc. that stores
the values within them
•Classes are reference data types
choices[]
⋮
poll
lead
Poll object
References
•An object can be shared across
multiple references
• This is accomplished via the usual
variable assignment (between
references)
• Ex: Poll poll1 = new Poll();
poll1
question1
⋮
Poll poll2 = poll1;
•A reference on the right-hand side of an
assignment operation does not create a
new object
Poll object
poll2
References
•An object can be manipulated through one of
its many references
poll1
question2
•Changes done in one reference are visible to
all other references of the object
• Ex: After performing
poll2.setQuestion(“question2”),the
question that will be obtained in poll1 will
be “question2”
⋮
Poll object
poll2
References
•When used between two references,
the comparison operator tests whether
the references shares the same object
poll1
question2
⋮
•The expression poll1 == poll2 is
true if the two references share a single
object
Poll object
poll2
References
•The expression poll1 == poll2 is false if
the two references have distinct objects
question
⋮
poll1
Poll object
•This is the case even though both objects
are structurally the same (e.g., have the
same contents)
question
⋮
•Do not use == to compare distinct objects
for equality (more on equality testing
later)
poll2
Poll object
The this variable
public class Poll {
String question = "";
String choices[] = new String[2];
int votes[] = new int[2];
int choicesCount = 0;
int currentVotes = 0;
int maxVotes;
int lead = -1;
•Inside any method of a class, a
special reference variable called
this is accessible
public String getQuestion() {
return this.question;
}
public void setQuestion(String question) {
this.question = question;
}
public String[] getChoices() {
// Output the array of choices
}
public boolean addChoice(String newChoice){
// Store more choice
}
public boolean hasChoice(String choice){
// Check if the input is a choice
}
public boolean vote(String choice){
// Add a vote to the given choice
}
•The this variable holds the object
being manipulated by the method
• The object held by this changes
relative to the object being considered
in the program
/* More function follows */
}
The this variable
public class Poll {
String question = "";
String choices[] = new String[2];
int votes[] = new int[2];
int choicesCount = 0;
int currentVotes = 0;
int maxVotes;
int lead = -1;
•Consider the following code :
public String getQuestion() {
return this.question;
}
public void setQuestion(String question) {
this.question = question;
}
public String[] getChoices() {
// Output the array of choices
}
public boolean addChoice(String newChoice){
// Store more choice
}
public boolean hasChoice(String choice){
// Check if the input is a choice
}
public boolean vote(String choice){
// Add a vote to the given choice
}
Poll poll1 = new Poll();
Poll poll2 = new Poll();
poll1.setQuestion(“Q1?”);
poll2.setQuestion(“Q2?”);
•In the first call to setQuestion(), the
object held by this is the object held by
poll1
• Changes performed in setQuestion()
only affects the object of poll1
•In the second call, the object held by
this is the object held by poll2
/* More function follows */
}
Download