Hey ferf, I wanted to add something since your code samples puzzle me a bit.
I'll just keep it short, but it can help you a lot if you are new to object oriented programming.
When you deal with generic abstractions of something (such as the Animal class representing a generic animal) it's a bad habit to keep irrelevant information bundled with the class.
Rather, what you should strive for is something called seperation of concern, which basically means seperating responsibility of your program into bits that fit together, rather than trying to jumble everything into one method/class etc.
As an example, in your previous code you jumbled all details of animals being omnivores, carnivores or herbivores into the same class and then set whichever field to true in order to represent their eating habits.
Like this:
Code
class Animal {
boolean omnivore;
boolean carnivore;
boolean herbavore;
String check() {
if(omnivore == true) return "omnivore";
if(carnivore == true) return "carnivore";
if(herbavore == true) return "herbavore";
}
}
class Animal2 {
public static void main(String args[]) {
Animal dog = new Animal();
Animal tiger = new Animal();
Animal skunk = new Animal();
dog.omnivore = true;
tiger.carnivore = true;
skunk.herbavore = true;
System.out.println("Dog is a " + dog.check());
System.out.println("tiger is a " + tiger.check());
System.out.println("Skunk is a " + skunk.check());
}
}
However, since most object oriented languages support inheritance, it is much cleaner to implement a check such as this by having seperate classes for each possibility, each doing their own check for what type of animal you're dealing with.
Obviously the check is being done on which type of object it is when you call the check method, but that doesn't matter to you as the programmer.
The code for seperating the concern of checking the type of eating habit an animal has, would be done this way:
Code
abstract class Animal {
abstract String check();
}
class Omnivore extends Animal {
String eats = "omnivore that eats everything";
// Has to implement this method since it derives from the abstract Animal class.
String check() {
return eats;
}
}
class Carnivore extends Animal {
String eats = "carnivore that eats meat.";
// Has to implement this method since it derives from the abstract Animal class.
String check() {
return eats;
}
}
class Herbivore extends Animal {
String eats = "herbivore that eats plants.";
// Has to implement this method since it derives from the abstract Animal class.
String check() {
return eats;
}
}
class Main {
public static void main(String args[]) {
Animal dog = new Omnivore();
Animal tiger = new Carnivore();
Animal skunk = new Herbivore();
System.out.println("Dog is an " + dog.check());
System.out.println("Tiger is an " + tiger.check());
System.out.println("Skunk is an " + skunk.check());
}
}
Best regards.
This post was edited by Klexmoo on Apr 25 2016 06:04am