Objects and
Classes
[When
asked] "...why is it called a class?" ... I reply "Because that's
the place
where
we teach objects how to do things".
--Rich Pattis
A class is a blueprint
for a collection of objects. A class describes a
collection
of objects that have similar attributes and behaviors.
An object, a.k.a. an instance
of a class, is a specific element from the collection of similar
objects.
Example: Dog (a real-world
class - a collection of similar objects, in this case, a collection of
similar animals)
- Every class has associated data, or attributes.
- Attributes for Dog
class:
breed, color, height, weight, gender, name
- Every class has associated actions.
- Actions for Dog class: bark, sleep,
eat
Instances of the Dog class, or objects in the Dog class:
my dog Otis,
your
dog, former president Bill Clinton's dog Buddy
The attributes for the Dog class can
be assigned specific values for each Dog object:
Attributes for my Dog Otis:
- breed = "custom"
- color = "black"
- height = 2.5 (feet)
- weight = 55 (pounds)
- gender = 'm'
- name = "Otis"
If we translate the Dog class into its Java version, we get this class:
public class Dog
{
//
The state, or data stored in an object
private String breed;
private String name;
private double height;
private double weight;
private char gender;
// In order to be able to create specific Dog instances,
or
objects of type Dog, we need a
//
method
(a
constructor) that creates an
instance:
public Dog(String theName, char theGender)
{
name = theName;
gender = theGender;
}
//
These
public,
non-static methods carry out each Dogs behavior
public void bark()
{
System.out.println("Rff, rff");
}
public void sleep()
{
System.out.println("zzzz, zzzz");
}
public void eat()
{
System.out.println("slurp");
}
}
Now if I'm writing a program, I can create a Dog
object:
Dog
otis
=
new
Dog("Otis", 'm');
// this object is a software
representation
of my dog Otis
I can call the methods that were defined in the Dog
class on my Dog
instance:
otis.bark();
// output to screen: Rff, rff
To create an instance of any class: Use the new operator and invoke the
constructor.
new
ClassName(...
any
needed
parameters... )
- The use of the new keyword
causes the creation, or construction, of a
new
object.
- The object is an instance
of the specified class.
- When new is
used,
a constructor for the class is
called.
- Remember that a constructor has the same name as
the class.
What's In a Class?
We're using the word "Class" in two different ways now:
- Class = module of a program, or an entire program
- Class = a blueprint, or general description, of a
collection of similar objects
We are beginning to explore object-oriented programming
- in which a program is considered as interaction between different
objects. Up until now, we have thought primarily about how to break a
program into a logical sequence of sub-programs, or procedures, that
each solve a part of the problem.
A class is a blueprint for a
set of objects. Every class in Java should contain:
- state, or
the data that should be stored for each object of this type
- behavior, or
the actions (methods) that each object of this type should be able to
carry out
- constructor(s),
special
method(s)
that
initialize the data fields in new objects when
they are created
Behavior
-
Defining
Non-static
Methods
An instance method definition contains:
1. An access specifier (like
public or private)
- determines which other methods can call
your
method
- most methods are declared public, so that
all
other methods in your program can call them
2. The return type
of the
method ( like void - which means no value is
returned
- or int, String, etc)
3. The name of the method
(such as bark)
4. A list of the parameters of
the method, enclosed in parentheses. The information the method needs
to carry out its operations
- the constructor for Dog takes the Dog's
name
and gender, and uses those values in the body of the method
5. The body of
the method,
which is enclosed in curly braces - a
sequence
of statements
Syntax:
accessSpecifier class ClassName
{
....
accessSpecifier
returnType
methodName
(parameterType
parameterName, ... )
{
//method body
}
...
}
Example:
public class
Speaker
{
...
public String sayHi()
{
String message = "Hello Friend";
return message; // this method
returns
to the caller a reference to String message
}
}
Recall: A method's execution
ends when a return statement is executed.
The
return value becomes the value of the method call expression.
What can we do with our Speaker class? We can compile it. But we cannot
run
it, because it does not contain a main method. So we write a test class
-
a class with a main method that allows us to try out the Speaker class.
Example:
public class
SpeakerTest
{
public static void main(String[] args)
{
// Create a new Speaker
Speaker friendly = new Speaker();
System.out.println(friendly.sayHi());
}
}
So your program consists of these 2 classes. To run your program, you:
1. Make a subfolder for your program.
2. Make two files, one per class.
3. Compile both files.
4. Run the test program, the file that contains the main method.
State -Defining Instance Fields
Let's add some data to our Speaker class:
public class
Speaker
{
private
String
name;
// the name of the person to
speak to
public
String
sayHi()
{
String
message
=
"Hi " + name;
return
message;
}
}
An instance field contains:
1. Acess specifier (typically private)
2. Type of the variable (e.g., String, int, double)
3. Variable name
Typically, we want instance fields in our classes to be private. This
allows us to control access to our data - a user can only change the
data stored in our instance variables in ways that are enabled by the
methods in the class. This is called data or implementation hiding, or encapsulation.
Syntax for Instance Variables:
accessSpecifier
Type
varName;
Constructors
We now need to change our Speaker class so that we can construct
Speaker objects with different names:
class Speaker
{
public
Speaker(String
personName)
// a
constructor for the Speaker class
{
name
=
personName;
}
... // the stuff we included before
}
A constructor allows us to create instances of our class. The
constructor
has the same name as the class, and is typically public.
Note: A constructor does not
have a return type.
Example: Using our constructor... code
from our test class' main method
To create an instance of Speaker class:
Speaker
mrFred
=
new
Speaker("Mr. Fred");
mrFred.sayHi();
//
output:
Hi
Mr. Fred
Example: Write a class that
represents a circle. Write another class to
test the Circle class.
What attributes does every circle have? (Instance variables)
What actions should every circle be capable of? (methods)
What initializations should be done when we create a new circle?
(constructors)