Lecture Notes. Creating a Simple Java Class

Total Page:16

File Type:pdf, Size:1020Kb

Lecture Notes. Creating a Simple Java Class

Lecture Notes. Creating a Simple Java Class

This class is used to represent a cat. For now the class only stores the cat’s name and weight.

Cat Class package cis260.matos; public class Cat { // defining a SIMPLE cat class // to be expanded soon...

// class variables private String name; private double weight;

// constructor(s) public Cat (String theName, double theWeight) { name = theName; weight = theWeight; }

public Cat (String theName) { name = theName; weight = 7; }

public Cat (double theWeight) { name = "N.A."; weight = theWeight; }

public Cat() { name = "****"; weight = 0; }

// mutators public String getName() { return (name); }

public void setName(String theName) { name = theName; }

public double getWeight() { return (weight); }

public void setWeight(double theWeight) { weight = theWeight; } // user-defined methods public void showData() { System.out.println("Name:\t\t" + name + "\nWeight:\t\t" + weight); } }

Driver Class package cis260.matos; public class CatDriver {

/** * testing a home-made Cat class */ public static void main(String[] args) {

Cat c1 = new Cat("Fluffy", 20); c1.showData();

Cat c2 = new Cat(); c2.setName("Leo"); c2.setWeight(10.5); c2.showData();

Cat c3 = new Cat("Dragon"); c3.showData();

Cat c4 = new Cat(9.5); c4.showData();

String myCatName = c1.getName(); System.out.println(myCatName);

}

}

Results

Name: Fluffy Weight: 20.0 Name: Leo Weight: 10.5 Name: Dragon Weight: 7.0 Name: N.A. Weight: 9.5 Fluffy

Recommended publications