I have this code for example, i have a super abstract class animal and a abstract subclass bird, and a subclass of bird AmericanRobin, i want to fill data in american robin to create the object bird from animal but i don't know how to do it because i want to create another subclass of bird called Domestic canary and pass the values from his constructor to his superclass constructor to create an object, any advice??
public abstract class Animal {// SuperClass animal
private String Kind,Appearance;
Animal(String Kind,String Appearance) {
this.Kind = Kind;
this.Appearance = Appearance;
}
public abstract void eat();
public abstract void move();
#Override public String toString() {
return "("+Kind+","+Appearance+")";
}
public abstract class Bird extends Animal {//SubClass of superClass Animal
Bird(String Kind, String Appearance) {
super(Kind, Appearance);
}
#Override public void eat() {
System.out.println("Eats seeds and insects");
}
#Override public void move() {
System.out.println("Flies throught the air");
}
}
public abstract class Fish extends Animal{//SubClass of SuperClass Animal
Fish(String Kind, String Appearance){
super(Kind,Appearance);
}
#Override public void eat() {
System.out.println("Eats krill, algae and insects");
}
#Override public void move() {
System.out.println("Swims throught the water");
}
}
//== Here the pain begins ==
public class AmericanRobin extends Bird {
AmericanRobin(String Kind, String Appearance) {
super(Kind, Appearance);
}
}
public class DomesticCanary extends Bird{
DomesticCanary(String Kind, String Appearance) {
super(Kind, Appearance);
}
}
}
Please rename variables to distinguish them from class names. kind and appearance are better names.
To test your inheritance structure, try creating an instance of subclass and call a method that it inherits, in your case:
AmericanRobin americanRobin = new AmericanRobin("kind","appearance");
System.out.println(americanRobin.toString()); // inherited from Animal
Related
I have some related classes that implement the same method
class Dog {
public void speak() { System.out.println("Bark") }
}
class Cat {
public void speak() { System.out.println("Meow") }
}
90% of the time, users would want both the dog and the cat to speak. They don't want to know the details. When we add a new animal, they'll want it to speak too. The idea is to avoid:
// All animals need to be explicitly told to speak every time
new Dog().speak();
new Cat().speak();
// But we just added Birds, and the users need to remember to add this call everywhere
new Bird.speak();
I could do something like
class Animals {
public void speak() {
new Dog().speak();
new Cat().speak();
new Bird().speak();
}
}
So that users can just call new Animals().speak() every time.
However, 10% of the time, it does need to be configurable. What I want is a way for users to do something like this
// Used most of the time
Animals.withAllAnimals().speak();
// Sometimes they don't want cats, and they want the dogs to woof instead
Animals.exclude(Cat)
.configure(Dog.sound, "Woof")
.speak();
How can I structure my classes to accomplish this?
I know that it is question tagged with java. However, let me show an example with C# as these languages have many common things.
The first thing is I would use inheritance and create abstract class Animal as common behaviour Speak() is used. So, abstract class should define behavior, and the derived classes should implement that behavior:
public abstract class Animal
{
public abstract void Speak();
}
Then just use inheritance and override behaviour in derived classes:
public class Bird : Animal
{
public override void Speak()
{
System.Console.WriteLine("I am a bird!");
}
}
public class Cat : Animal
{
public override void Speak()
{
System.Console.WriteLine("I am a cat!");
}
}
public class Dog : Animal
{
public override void Speak()
{
System.Console.WriteLine("I am a dog!");
}
}
Then we need a class that allows to speak for all animals. Let's create Choir class for this purpose:
public class Choir
{
private List<Animal> choristers;
public void AddChoristers(IEnumerable<Animal> choristers)
{
if (choristers == null)
choristers = new List<Animal>();
choristers.AddRange(choristers);
}
public void SpeakAll()
{
foreach (Animal animal in choristers)
animal.Speak();
}
public void Speak(Func<Animal, bool> filter)
{
IEnumerable<Animal> filteredAnimals = choristers
.Where(filter ?? (animal => true));
foreach (Animal animal in filteredAnimals)
animal.Speak();
}
}
Pay attention to Speak() method. It can take a predicate as a parameter, so you can choose desired animals to speak().
Here are some ideas.
import java.util.*;
import java.util.function.Consumer;
/**
* An animal can either speak with its own voice, or another supplied
*/
interface Animal {
String speak();
String speak(String voice);
}
/**
* Base class for animal implementations.
*
* An animal is added to a Menagerie when created.
*/
abstract class BaseAnimal implements Animal {
private final String defaultVoice;
public BaseAnimal(Menagerie menagerie, String defaultVoice) {
this.defaultVoice = defaultVoice;
menagerie.add(this);
}
public String speak(String voice) {
return voice;
}
public String speak() {
return speak(defaultVoice);
}
}
/**
* A Dog. Even when given a voice the dog does things slightly differently.
*/
class Dog extends BaseAnimal {
public Dog(Menagerie menagerie) {
super(menagerie, "Bark!");
}
public String speak(String voice) {
return voice + " (and drools)";
}
}
/**
* A collection of animals. We can do something side-effectful to each, or create a new collection where
* some classes of animal are excluded or have different behaviour.
*/
interface Animals {
void forEach(Consumer<Animal> action);
Animals exclude(Class<Animal> clazz);
Animals configureVoice(Class<Animal> clazz, String voice);
}
/**
* An Animals instance which can contain only a single animal of each class
* (an arbitrary decision based on the code in the question)
*/
class Menagerie implements Animals {
Map<Class<? extends Animal>,Animal> animals = new HashMap<>();
public Menagerie() {
}
public Menagerie(Map<Class<? extends Animal>, Animal> animals) {
this.animals = new HashMap<>(animals);
}
public void add(Animal animal) {
animals.put(animal.getClass(), animal);
}
public void forEach(Consumer<Animal> action) {
animals.values().forEach(action);
}
#Override
public Animals exclude(Class<Animal> clazz) {
Menagerie m = new Menagerie(animals);
m.animals.remove(clazz);
return m;
}
/**
* Return an Animals instance which contains a proxy for a particular type of animal
* which will behave differently when speak() is called.
*/
#Override
public Animals configureVoice(Class<Animal> clazz, String voice) {
Menagerie m = new Menagerie(animals);
Animal a = m.animals.get(clazz);
if (a != null) {
m.animals.put(clazz, new Animal() {
#Override
public String speak() {
return voice;
}
#Override
public String speak(String voice) {
return a.speak(voice);
}
});
}
return m;
}
}
To access sub-class method down-casting is needed, is there is a way to achieve this using generic without type-casting in same manner.
public class Main {
public static void main(String[] args){
Animal parrot = new Bird();
((Bird)parrot).fly();
}
}
interface Animal{
void eat();
}
class Bird implements Animal{
#Override
public void eat() {}
public void fly(){}
}
public class Main {
public static void main(String[] args){
Animal parrot = new Bird();
parrot.move();
}
}
interface Animal{
void eat();
void move();
}
class Bird implements Animal{
#Override
public void eat() {}
public void move(){fly();}
public void fly(){}
}
It could work with something like this I guess
Interfaces are meant to add methods to implemented classes without defining actual code for this method, meaning that any implemented class will definitely have the same methods but 2 implemented methods with the same name won't necessarily perform the same action.
To explain it with the current thread it would be:
interface Animal {
void move();
}
class Bird implements Animal{
public void move(){
fly();
}
}
class Dog implements Animal{
public void move(){
walk();
}
}
This way, each class will have its own definition of the move method while in main each method will be called by object.move().
This way of doing things allows to go from a code like this
for (object tmp:objList){
if(tmp.class=="Bird")
tmp.fly();
}
else if (tmp.class=="Dog"){
tmp.walk();
}
...
}
to
for (object tmp:objList){
tmp.move();
}
The parrot class should extend the Bird class, then you can call the fly method from a parrot object directly and without need to cast.
public class Parrot extends Bird{
//have some filed or method
}
I have several classes with differently object type cat, dog and horse. I have
one root class where is method doSomethig with only one parameter which I want to call in rest of classes. How to write the method without type conflict. This is only example.
Cat cat;
Dog dog;
Horse horse;
protected void doSomething(one parameter){
cat.doMeow();
dog.doBark();
horse.run();
}
Why not to extend parent class Animal where there would be doSomething(one parameter) and then in subclasses call super() ?
If I understand you right, the signature is fixed for just one parameter. But you need to have access to cat, dog and horse? In that case, you need to adjust one to be a parameter object.
(Also, it should start with an upper case letter, as general accepted code style)
public class one
{
private Cat cat;
private Dog dog;
private Horse horse;
public one(Cat cat, Dog dog, Horse horse)
{
this.cat = cat;
this.dog = dog;
this.horse = horse;
}
public Cat getCat()
{
return this.cat
}
// getDog(), getHorse()
}
Then use the getter methods in the doSomething method
protected void doSomething(one parameter){
parameter.getCat().doMeow();
parameter.getDog().doBark();
parameter.getHorse().run();
}
Calling it like:
public void myMethod()
{
one animals = new one(new Cat(), new Dog(), new Horse());
doSomething(animals); // if same class or myInstance.doSomething(animals) if another class
}
A brute force solution would be to pass an Object, e.g. of type Animal and check the type in the method, and call the appropriate method based on the result of the type check:
protected void doSOmething(Animal an Animal) {
if( anAnimal instanceof Horse)
((Horse) anAnimal).run();
else if( anAnimal instanceof Dog )
((Dog) anAnimal).bark();
else ...
}
However, this is considered to be bad style, because the method has too much knowledge about Horses, Dogs, and such.
It would be better if Animal had an abstract method doDefaultAction() which is overwritten by the Horse as a call to run(), by the dog as a call to bark(), and so on.
abstract class Animal {
abstract void doDefaultAction(Animal anAnimal);
}
class Horse extends Animal {
#Override
void doDefaultAction(Animal anAnimal) {
((Horse) anAnimal).run();
}
void run() { /* do some running */ }
}
In your method doSomething() you would simply call anAnimal.doDefaultAction() without need to know what the default action for the animal might be.
If the abstract Animal class does not do something else you might also consider to use an interface Animal instead of a class.
You could create a common interface and call the interface method. For example:
public interface Animal {
public void act();
}
public class Cat implements Animal {
public void doMeow() { /* ... */ }
#Override
public void act() {
doMeow();
}
}
public class Dog implements Animal {
public void doBark() { /* ... */ }
#Override
public void act() {
doBark();
}
}
Then the doSomething method could polymorphically call the act method:
protected void doSomething(Animal animal) {
animal.act();
}
Depending on which object is passed (e.g. Cat or Dog), the behavior of doSomething will change.
Assuming this is the classic OO inheritance example. A simple solution works like this:
public class AnimalExample {
interface Animal {
void action();
}
public static class Cat implements Animal{
#Override
public void action() {
System.out.println("meow");
}
}
public static class Dog implements Animal{
#Override
public void action() {
System.out.println("bark");
}
}
public static class Horse implements Animal{
#Override
public void action() {
System.out.println("run");
}
}
static void doSomething(Animal animal){
animal.action();
}
public static void main(String[] args) {
Cat cat = new Cat();
Dog dog = new Dog();
Horse horse = new Horse();
doSomething(cat);
doSomething(dog);
doSomething(horse);
}
}
Imagine a simple hierarchy:
abstract class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}
I want to implement abstract method makeNoise, so that Dog could override it to print Woof! and Cat could override it to print Meow!.
I wrote the following code:
abstract class Animal {
abstract void makeNoise();
}
class Dog extends Animal {
#Override
void makeNoise() {
System.out.println("Woof!");
}
}
class Cat extends Animal {
#Override
void makeNoise() {
System.out.println("Meow!");
}
}
But I don't like it. I repeat sout in overriden methods.
I would like to create an abstract final static variable named SOUND in Animal and override it in the children:
abstract class Animal {
abstract static final String SOUND;
void makeNoise() {
System.out.println(SOUND);
}
}
class Dog extends Animal {
static final String SOUND = "Woof!";
}
class Cat extends Animal {
static final String SOUND = "Meow!";
}
But that code obviously doesn't work. But is it a way to create a logic such like this, so I can could create the following code:
new Dog().makeNoise(); // Woof!
new Cat().makeNoise(); // Meow!
UPDATE
Besides makeNoise I also want to get access to a sound statically, so that I can also write the following code:
System.out.println("Dog says: " + Dog.SOUND);
System.out.println("Cat says: " + Cat.SOUND);
abstract class Animal {
void makeNoise() { System.out.println(noise()); }
abstract String noise();
}
class Dog extends Animal {
#Override
String noise() { return "Woof!"; }
}
class Cat extends Animal {
#Override
String noise() { return "Meow!"; }
}
That's as good as you'll get.
Sometimes, I came across some class design as follow.
abstract class animal {
public abstract void speak();
}
class dog extends animal {
#Override
public void speak() {
// Do something.
}
}
abstract class abstract_dog extends dog {
#Override
public abstract void speak();
}
I was wondering, what is the purpose of having an abstract_dog class? Why we "transform" the non-abstract speak method into abstract speak again?
In case you want to create a base class that forces people to override speak, but inherits Dog.
I agree with SLaks, and think that this would be a real life situation:
abstract class animal {
public abstract void speak();
}
class dog extends animal {
#Override
public void speak() {
// Dog says 'bark'
}
}
abstract class abstract_dog extends dog {
#Override
public abstract void speak();
}
class poodle extends abstract_dog {
#Override
public void speak() {
// poodle says 'yip yip'
}
}
class great_dane extends abstract_dog {
#Override
public void speak() {
// great dane says 'ruff ruff'
}
}
I think you would use this in the case where you want the make a new child class implement the speak method and the dog class may have other methods that the new child class would not have to implement.
Knowing more about your exact situation would help in determining if there is a better design for this scenario.