In Java
Lab 26.1
Object-oriented languages like Java are designed to make it easy
for programmers to implement software versions of real-world
objects. In learning Java, an important skill to master is the
ability to represent an object in code. Objects that we model are
described using Java classes, so we have chosen to begin this lab
by modeling a very simple, everyday object: a door.
Starting with a new Eclipse project, add a class that models a door
object, without a main method.
Don’t worry about the internal details just yet. Just give the
class a name (Door) and an empty body (below) for
the moment.
We will add more to the class shortly.
public class Door
{
} // end class Door
Lab 26.2
When modeling an object as a class, we also need to describe the
properties it possesses. An everyday object that we wish to model
always has one or more properties that describe it. For instance a
door object might have a name
like Front or Side to
distinguish it from other doors. Another property that could
describe a door is its
state: open or closed (or, open or not-open).
Properties of objects are described in code by using nouns
like state or name to
create instance variables that hold values.
Add instance (member) variables to
your Door class for the name of the door
and its state. Note that we
declare state as
a boolean since it's
either open or closed (not
open):
public class Door
{
private String name;
private boolean state; // true for
open, false for closed
} // end class Door
Lab 26.3
Objects also have operations which can be invoked on the object
and which may change the object in some way. For instance, the
operations for a door object could
be open and close.
An operation on an object corresponds to a Java method and is
described in code by using a verb
like open or close.
Invoking a method may change the value of an instance variable. For
example, invoking close() would change
the value of the state variable
from true (open)
to false (closed).
Declare member methods
for open and close:
public class Door
{
private String name;
private boolean state; // true for
open, false for closed
public void setName(String n)
{
name = n;
} // end name setter
public boolean isOpen()
{
return state;
} // end state getter
public void open()
{
state = true;
} // end open method
public void close()
{
state = false;
} // end close method
} // end class Door
Lab 26.4
Add a main (application) class to your project and add
code to the main method that does the
following:
In Java Lab 26.1 Object-oriented languages like Java are designed to make it easy for programmers to implement software
-
answerhappygod
- Site Admin
- Posts: 899604
- Joined: Mon Aug 02, 2021 8:13 am
In Java Lab 26.1 Object-oriented languages like Java are designed to make it easy for programmers to implement software
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!