Introdução aos Objectos/Exercício 01: Gato simples
From Wiki**3
< Introdução aos Objectos
Problema
Modele e implemente uma classe que represente uma versão muito simples do conceito Gato.
Um Gato tem como características o nome, a idade e o peso.
Implemente o método de comparação (equals), por forma a considerar que dois gatos são iguais se as suas características forem iguais.
Implemente o método de apresentação (toString), por forma a produzir uma cadeia de caracteres onde seja apresentado o nome, a idade e o peso do gato.
Implemente métodos de acesso às variáveis internas do gato.
Implemente um programa ("main") que ilustre a utilização dos métodos anteriores.
Solução
Class "Cat"
<java5> public class Cat {
/** * The cat's name. */ private String name;
/** * The cat's age. */ private int age;
/** * The cat's weight. */ private double weight;
/** * Fully specify the cat's initial state. * * @param name * @param age * @param weight */ public Cat(String name, int age, double weight) { this.name = name; this.age = age; this.weight = weight; }
/** * @return the name */ public String getName() { return this.name; }
/** * @param name the name to set */ public void setName(String name) { this.name = name; }
/** * @return the age */ public int getAge() { return this.age; }
/** * @param age the age to set */ public void setAge(int age) { this.age = age; }
/** * @return the weight */ public double getWeight() { return this.weight; }
/** * @param weight the weight to set */ public void setWeight(double weight) { this.weight = weight; }
/** * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object o) { if (o instanceof Cat) { Cat cat = (Cat) o; return this.name.equals(cat.name) && this.age == cat.age && this.weight == cat.weight; } return false; }
/** * @see java.lang.Object#toString() */ @Override @SuppressWarnings("nls") public String toString() { return this.name + " (cat) (" + this.age + ":" + this.weight + ")"; } } </java5>
Test application (main)
<java5> public class Application { public static void main(String[] args) { Cat cat = new Cat("Tareco", 12, 3.141); System.out.println(cat.equals(new Cat("Tareco", 12, 3.141))); // prints "true" System.out.println(cat.equals(new Cat("Pantufa", 1, 2.718))); // prints "false" System.out.println(cat); } } </java5>