more java @ mlab, 10-17 Jan 2000, juhuu@katastro.fi
Objects (Classes) Objects in java are called classes. Classes can contain data and methods. These are referred to as class members Example of defining a class: // import all the classes you need to use. all the // classes in the same directory are imported automatically. // importing doesn't affect the size of the class, it merely // tells that the names of the classes to be used. // // in this example, we need java.awt.Image. the easy way to import // it is to use * (java.awt.*), it imports all the classes found in // awt package. import java.awt.*; // the name of the class is Human (the names usually start with capital letter) public class Human { // this class has 3 data members int nWeight; String sName; Image imgPhoto; // the class constructor // // this method creates an instance of the class Human public Human (int weight, String s, Image img) { nWeight = weight; sName = s; imgPhoto = img; } // a method (function). this methods prints // the weight of the Human to java console // // void means that this method doesn't return a value. public void print_weight() { System.out.println("I weight: " + nWeight); } } // end of class Human // example of using class Human from another class public class OtherClass { // we have one Human variable called 'friend' Human friend; public init () { // put a new Human instance to friend friend = new Human(72, "Petteri", image_of_petteri); // call the print_weight function of the friend (Petteri) friend.print_weight(); // we can change the friend ; after this, the reference to Petteri is lost friend = new Human(80, "Jukka", image_of_jukka); // now we print the weight of Jukka friend.print_weight(); } }