Presentation is loading. Please wait.

Presentation is loading. Please wait.

Simple Classes in Java CSCI 392 Classes – Part 1.

Similar presentations


Presentation on theme: "Simple Classes in Java CSCI 392 Classes – Part 1."— Presentation transcript:

1 Simple Classes in Java CSCI 392 Classes – Part 1

2 Today's Objectives Scope of Variables and Methods public, private, and more Constructors Instance Variables and Class (static) Variables

3 Class Code usually goes in its own File
sample.java public class sample { main () widget bob = new widget; bob.somemethod(); } widget.java public class widget { blah blah blah } 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

4 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

5 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

6 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

7 Creating an Object Don't forget to call new() class MainProgram {
public void Main() list mylist1 = new list(); list mylist2 = new list(50); ...

8 "this" = this instance public class list { private int size; ...
public set_size (int size) this.size = size; }

9 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.

10 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; }

11 Q u i z Are variables and methods public or private by default?
Why do I need a constructor if I can initialize fields when I declare them? How is a "class" variable declared? Given "private static int BoxCount" is this legal: "this.BoxCount = 0;" ?


Download ppt "Simple Classes in Java CSCI 392 Classes – Part 1."

Similar presentations


Ads by Google