Simple Classes in Java
CSCI 392
Classes – Part 1
Today's Objectives
1. Scope of Variables and Methods
public, private, and more
2. Constructors
3. Instance Variables and
Class (static) Variables
Class Code usually goes in its own File
sample.java
widget.java public class sample
{
public class widget main ()
{ {
blah blah blah widget bob = new widget;
} bob.somemethod();
}
}
The file "widget.java" contains all the code for the
widget class. No main().
First, compile widget.java into widget.class
Sample.java does not need to "include" widget.java
or widget.class
Limiting Scope of Fields
Given a class named "list"...
public int size;
everyone can see size
private int size;
only list instances can see their size, default is private
protected int size;
only list instances and classes derived from list can
see size; i.e. somewhat private
public final double pi = 3.14;
pi is a constant visible to everyone
Constructors
Syntax is just like C++
public class list
{
private int size = 0; // field
public list () // constructor
{
size = 0;
}
Constructors are optional in Java (and C#)
this constructor sets size=0, which is the default anyway
Initializers
Since constructors are optional…
public class list
{
private int maxsize = 10; // set default
public list ()
{
maxsize = 10; // redundant
}
public list (int newmax)
{
maxsize = newmax; // override default
}
Creating an Object
Don't forget to call new()
class MainProgram
{
public void Main()
{
list mylist1 = new list();
list mylist2 = new list(50);
...
"this" = this instance
public class list
{
private int size;
...
public set_size (int size)
{
this.size = size;
}
Instance Variables vs Class Variables
Sometimes, you need one variable that belongs to the
entire class, not separate variables for each instance.
public class WarningBox
{
private String message;
private static int boxcount;
Each WarningBox instance has its own message, but
there is only one boxcount shared by all
WarningBoxes.
Static Methods
Operate on the class, not an individual instance.
Not allowed to access non-static variables.
static private boolean TooManyBoxes()
{
if (boxcount > 10)
return true
else
return false;
}
Quiz
1. Are variables and methods public or private by
default?
2. Why do I need a constructor if I can initialize fields
when I declare them?
3. How is a "class" variable declared?
4. Given "private static int BoxCount" is this legal:
"this.BoxCount = 0;" ?