Cannot code simple case without abstract static field overriding - java

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.

Related

Casting & Inheritance in Java [duplicate]

How can I call the eat and drink method of the Animal class with the myAnimal instance in the code?
public class Animal {
public void eat() {
System.out.println("Animal Eats");
}
public void drink() {
System.out.println("Animal Drinks");
}
}
public class Cat extends Animal {
#Override
public void eat() {
System.out.println("Cat Eats");
}
#Override
public void drink() {
System.out.println("Cat Drinks");
}
public static void main(String[] args) {
Cat myCat = new Cat();
myCat.eat();
myCat.drink();
Animal myAnimal = myCat;
myAnimal.eat();
myAnimal.drink();
}
}
Output that I am getting:
Cat Eats
Cat Drinks
Cat Eats
Cat Drinks
This is my expected output:
Cat Eats
Cat Drinks
Animal Eats
Animal Drinks
You cannot do what you want. The way polymorphism works is by doing what you are seeing.
Basically a cat always knows it is a cat and will always behave like a cat regardless of if you treat is as a Cat, Felis, Felinae, Felidae, Feliformia, Carnivora, Theria, Mammalia, Vertebrata, Chordata, Eumetazoa, Animalia, Animal, Object, or anything else :-)
Here you will have an option to choose which method do you want to invoke:
public class Cat extends Animal {
public void superEat() {
super.eat();
}
public void superDrink() {
super.drink();
}
#Override
public void eat() {
System.out.println("Cat Eats");
}
#Override
public void drink() {
System.out.println("Cat Drinks");
}
}
This line:
Animal myAnimal = myCat;
assigns the variable myAnimal to the object myCat, which you've created before. So when you call myAnimal.eat() after that, you're actually calling the method of the original myCat object, which outputs Cat Eats.
If you want to output Animal Eats, you'll have to assign an Animal instance to a variable. So if you would do this instead:
Animal myAnimal = new Animal()
the variable myAnimal will be an instance of Animal, and thus will overwrite the previous assignment to Cat.
If you will call myAnimal.eat() after this, you're actually calling the eat() method of the Animal instance you've created, which will output Animal Eats.
Concluding: your code should read:
public class Cat extends Animal {
#Override
public void eat() {
System.out.println("Cat Eats");
}
#Override
public void drink() {
System.out.println("Cat Drinks");
}
public static void main(String[] args) {
Cat myCat = new Cat();
myCat.eat();
myCat.drink();
Animal myAnimal = new Animal();
myAnimal.eat();
myAnimal.drink();
}
}
Access to static fields, instance fields and static methods depends on the class of reference variable and not the actual object to which the variable points to.
Remember that member variables are shadowed, not overridden.
This is opposite of what happens in the case of instance methods.
In case of instance methods the method of the actual class of the object is called.
class ABCD {
int x = 10;
static int y = 20;
public String getName() {
return "ABCD";
}
}
class MNOP extends ABCD {
int x = 30;
static int y = 40;
public String getName() {
return "MNOP";
}
}
public static void main(String[] args) {
System.out.println(new MNOP().x + ", " + new MNOP().y);
ABCD a = new MNOP();
System.out.println(a.x); // 10
System.out.println(a.y); // 20
System.out.println(a.getName()); // MNOP
}
In this example although the the object myCat is assigned to an Animal object reference, (Animal myAnimal = myCat) the Actual object is of type Cat and it behaves as it's a cat.
Hope this helps.
You can create constructor for class Animal, that takes another Animas as parameter, and creates new instance based on provided one.
public class Animal {
//some common animal's properties
private int weight;
private int age;
public Animal() {
// empty.
}
public Animal(final Animal otherAnimal) {
this.weight = otherAnimal.getWeight();
this.age = otherAnimal.getAge();
}
public void eat() {
System.out.println("Animal Eats");
}
public void drink() {
System.out.println("Animal Drinks");
}
// setters and getters.
}
public class Cat extends Animal {
#Override
public void eat() {
System.out.println("Cat Eats");
}
#Override
public void drink() {
System.out.println("Cat Drinks");
}
public static void main(String[] args) {
Cat myCat = new Cat();
myCat.eat();
myCat.drink();
// note: myAnimal is not a Cat, it's just an Animal.
Animal myAnimal = new Animal(myCat);
myAnimal.eat();
myAnimal.drink();
}
}
Few suggestions :
Don't pass child class reference to super class and except super class method has to be invoked for overridden method. Call super class methods from super class instance.
Animal myAnimal = new Animal();
myAnimal.eat();
If you want to call super class method from child class, explicitly call super class method name with super.methodName();
public void eat() {
super.eat();
System.out.println("Cat Eats");
}
Don't override super class method in child class. Always super class method is invoked.
If you make methods in each class static, it should work.
public class Animal {
public static void eat() {
System.out.println("Animal Eats");
}
public static void drink() {
System.out.println("Animal Drinks");
}
}
public class Cat extends Animal {
#Override
public static void eat() {
System.out.println("Cat Eats");
}
#Override
public static void drink() {
System.out.println("Cat Drinks");
}
public static void main(String[] args) {
Cat myCat = new Cat();
myCat.eat();
myCat.drink();
Animal myAnimal = myCat;
myAnimal.eat();
myAnimal.drink();
}
}
The above code will give the following output
Cat Eats
Cat Drinks
Animal Eats
Animal Drinks
You can achieve what you want using the super keyword, which allows to access the overridden method.
public class Animal {
public void eat() {
System.out.println("Animal Eats");
}
public void drink() {
System.out.println("Animal Drinks");
}
}
public class Cat extends Animal {
public void eat() {
System.out.println("Cat Eats");
}
public void drink() {
System.out.println("Cat Drinks");
}
public void printMessage(){
super.eat();
super.drink();
}
public static void main(String[] args) {
Cat myCat = new Cat();
myCat.eat();
myCat.drink();
myCat.printMessage();
}
}
Please don't vote on this answer... you can vote on the other one :-) This is a bad answer, but shows how you would do what you are trying to do... poorly.
public class Main
{
public static void main(final String[] argv)
{
Child child;
Parent parent;
child = new Child();
parent = child;
child.a();
parent.a();
child.otherA();
parent.otherA();
}
}
class Parent
{
public void a()
{
System.out.println("Parent.a()");
}
public void otherA()
{
// doesn't matter what goes here... really should be abstract
}
}
class Child
extends Parent
{
#Override
public void a()
{
System.out.println("Child.a()");
}
#Override
public void otherA()
{
super.a();
}
}
public class Main {
public static void main(String[] args) {
Cat myCat = new Cat();
myCat.eat();
myCat.drink();
Animal myAnimal = new Animal();
myAnimal.eat();
myAnimal.drink();
}
}
public class Animal {
public void eat(){
System.out.println("Animal eat() called");
}
public void drink(){
System.out.println("Animal drink() called");
}
}
public class Cat extends Animal {
#Override
public void eat() {
System.out.println("Cat eat() called");
}
#Override
public void drink() {
System.out.println("cat drink() called");
}
}
OUTPUT:
Cat eat() called
cat drink() called
Animal eat() called
Animal drink() called
You need to create an object of the super class Animal OR another option is to use the keyword super in the child class methods e.g., super.eat() or super.drink()
Cat can't stop being a cat, even if it is an animal. Cat will eat and cat will drink in a cat's way. It might be similar to what an Animal does, which is why it overrides the method. If you want it to do what the animal does by default, don't override. You could probably do some weird stuff with reflection and make separate methods that access the parent methods such as:
public void superDrink() {
Animal.class.getMethod("drink").invoke();
}
but that might be overkill don't you think?
Of course that probably wouldn't work since it's not static.
You can do what you want with a few minor changes to your code. Naturally the methods of the Animal class have been overriden and you cannot simply access them by changing the reference type. Instead, you could slightly change the definition of the eat and drink functions as follows.
class Animal{
public void eat(boolean randomBoolean){
System.out.println("Animal eats");
}
public void drink(boolean randomBoolean){
System.out.println("Animal drinks");
}
}
class Cat extends Animal{
public void eat(boolean wantOverriden){
if(wantOverriden){
boolean randomBooleanValue=true|false;
super.eat(randomBooleanValue);
}
else{
System.out.println("Cat eats");
}
}
public void drink(boolean wantOverriden){
if(wantOverriden){
boolean randomBooleanValue=true|false;
super.drink(randomBooleanValue);
}
else{
System.out.println("Cat drinks");
}
}
}
Now you should be able to access the overriden methods of the Animal class through the Cat class object by simply passing in a boolean value indicating if you want to do so ex:
Cat c=new Cat();
c.eat(false); //Indicating that you dont want to access the overriden method
c.drink(false); //Indicating that you dont want to access the overriden method
c.eat(true); //Indicating that you want to access the overriden method
c.drink(true); //Indicating that you want to access the overriden method

Is there any way to access a sub-type method without casting using generic

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
}

Is there a way to use overridden function in base class? (In Java)

I tried to implement a function in a base class which using the function of the childs (defiend as a abstract function in the base class). I think an example will demonstrate the problem in the best way.
abstract class Animal{
public void doSomthing(){
this.sound();
}
protected abstract void sound();
}
class Dog extends Animal{
#Override
protected void sound(){
System.out.println("WAF");
}
}
now when I tried to get the element in run time (by factory method which looks like: Animal factory method("Dog);) and call to the doSomthing method I got exception because it goes to the abstract method, my question is if there is any way the bypass this or another solution for this problem.
class myMain
{
public static void main(String[]args)
{
Animal doggo = new Dog(); // create object for dog
doggo.animalSound(); // call the sound for dog
}
}
class Animal
{
public void animalSound()
{
System.out.println("The animal makes a sound");
}
}
class Dog extends Animal
{
public void animalSound()
{
System.out.println("The Dog Says bow wow! ");
}
}
I do not see any problem with the approach you have mentioned in the description of your question. Maybe you are doing some other mistake. Check the following working code:
abstract class Animal {
public void doSomthing() {
sound();
}
protected abstract void sound();
}
class Dog extends Animal {
#Override
protected void sound() {
System.out.println("WAF");
}
}
class AnimalFactory {
static Animal animal;
public static Animal factoryMethod(String animalName) {
if ("Dog".equals(animalName)) {
animal = new Dog();
}
return animal;
}
}
class Main {
public static void main(String[] args) {
Animal animal = AnimalFactory.factoryMethod("Dog");
animal.sound();
}
}
Output:
WAF
The call to child class method from super class can be done.
Refer code snippet mentioned in below link:
Can a Parent call Child Class methods?

how to pass more types arguments into method with one parameter

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);
}
}

passing values from subclass of a subclass in java

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

Categories