Person
//
// Person.java
//
// The Person class is defined in Person.java
public class Person
{
// The constructor function is called when new Person object is
// created. Member variables should be initialized here. Note
// that constructors do not return a value.
public Person(String nameIn)
{
name = nameIn;
}
// public functions can be called from outside the class
public void greeting()
{
System.out.println("Hello, my name is " + name);
System.out.println("and I have " + noseCount + " nose.\n");
}
// public accessor functions can be used to give (read-only)
// access to private member variables
public String getName()
{
return name;
}
// private member variables cannot be accessed directly from
// outside the class
private String name;
// static == shared by all objects of the class
// final == variable cannot be changed (after initialization)
// e.g Math.PI and Math.E (public static final)
private static final int noseCount = 1;
}//
// PersonTest.java
//
public class PersonTest
{
public static void main(String[] args)
{
// create a new Person object
Person drkessner = new Person("Dr. Kessner");
// call the greeting() and getName() functions
drkessner.greeting();
System.out.println("That guy's name is " +
drkessner.getName() + "\n");
// create another Person object
Person gadget = new Person("Gadget");
gadget.greeting();
}
}
Output:
Hello, my name is Dr. Kessner
and I have 1 nose.
That guy's name is Dr. Kessner
Hello, my name is Gadget
and I have 1 nose.