Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languagejava
public class Main {
    public static void main(String[] args) {
        MyClass myObject = new MyClass("World");
        myObject.sayHello();  // Outputs: "Hello, World"
    }
}

Demo - Person Class

Code Block
languagejava
package Demo1PersonClass;
/**
 * @author Dr. Kevin Roark
 * Class contains attributes and methods for a Person
 */


public class Person {
    /*  -----------------------------------
     * Class Variables
      ----------------------------------- */
    private String firstName;
    private String lastName;
    private int age;

    /*
     * Constructors
      ----------------------------------- */
    public Person(String firstName, String lastName, int age) {
        super();
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

    public Person() {
        super();
        this.firstName = "Unknown FirstName";
        this.lastName = "Unknown LastName";
        this.age = -1;
    }


    /* -----------------------------------
     * Getter/Setters
      ----------------------------------- */
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }

	/*  -----------------------------------
	 * Class Methods
	   ----------------------------------- */
    /**
     * Function creates a string with labels and Object data
     * @return String
     */
    public String PrintInfo()
    {
        String myReturn = "";
        myReturn = "Name: " + this.getFirstName() + " " + this.getLastName() + "\n";
        myReturn += "Age: " + this.getAge();
        return myReturn;
    }
}

Driver

Code Block
languagejava
package Demo1PersonClass;

public class PersonDriver {
    public static void main(String[] args) {
        //Demo of using argument constructor
        Person myPersonOne = new Person("Kevin", "Roark", 61);
        System.out.println(myPersonOne.PrintInfo());

        //Demo of Default Constructor
        Person myPersonTwo = new Person();
        System.out.println(myPersonTwo.PrintInfo());

        //Now using the setters - give the default constructor some values
        myPersonTwo.setFirstName("Fred");
        myPersonTwo.setLastName("Flintstone");
        myPersonTwo.setAge(29);

        //now output the myPersonTwo that now has data
        System.out.println(myPersonTwo.PrintInfo());

    }
}

...