Sams Teach Yourself C in 21 Days

(singke) #1
A Simple Demonstration ..............................................................................

Before continuing with the details of class definitions, it is a good idea to see how to cre-
ate and use a simple class. This Java project will have two files. One, SimpleClass.java,
will define a very simple class that does nothing more than provide two properties, one
to store a number and the other to store some text. The second file,
ClassBasicsDemo.java, is a program that makes use of SimpeClass. The source code for
these two files is shown in Listings B5.1 and B5.2.

LISTINGB5.1 Code in SimpleClass.java
1: import java.lang.String;
2:
3: public class SimpleClass {
4:
5: public double data;
6: public String text;
7: }

LISTINGB5.2 Code in ClassBasicsDemo.java
1: public class ClassBasicsDemo {
2: public static void main(String args[])
3: {
4: SimpleClass MyClass;
5:
6: MyClass = new SimpleClass();
7: MyClass.data = 1.2345;
8: MyClass.text = “A class act.”;
9: System.out.print(“The number stored in MyClass is “);
10: System.out.println(MyClass.data);
11: System.out.print(“The text stored in MyClass is “);
12: System.out.println(MyClass.text);
13: }
14: }

The number stored in MyClass is 1.2345
The text stored in MyClass is A class act

726 Bonus Day 5

Just as with C++ member variables, you should make property variables pri-
vate and create two function to access it—one to get its value and one to
set is value.

Note


OUTPUT

40 448201x-Bonus5 8/13/02 11:23 AM Page 726

Free download pdf