how can i fix this? i need to set the type of animal and age of animal for every animal. look how i wrote the code, and please t | Sololearn: Learn to code for FREE!

+1

how can i fix this? i need to set the type of animal and age of animal for every animal. look how i wrote the code, and please t

abstract class animal{ String Type; int age; public abstract void voice(); } class dog extends animal{ Type = dog; age = 6; public static void voice(){ System.out.println ("BARK BARK!"); } } class cat extends animal{ Type = cat; age = 2; public static void voice(){ System.out.println ("mew mew"); } } public class Main { public static void main(String[] args) { dog d = new dog(); cat c = new cat(); System.out.println (d.Type + " , " + c.Type); } }

5/28/2020 10:01:33 AM

Yahel

5 Answers

New Answer

+2

In class dog and cat, you have not mentioned the data type for Type and age. Also why is your voice method made static while implementing it? The Type is a string so it must be put inside double quotes " ". Note: In inheritance you cannot override an instance variable because overriding was meant to update behavior and not the state of an instance. https://code.sololearn.com/chswMmlr51Jy/?ref=app

+1

class Person { // Below are instance variables which define the state of an object. String name; int age; // Below are methods which define the behaviour of an object. public void speak(){ System.out.println("speak"); } public void run(){ System.out.println("run"); } } Class Yahel extends Person { @Override public void speak(){ System.out.println("Yahel can speak"); } @Override public void run(){ System.out.println("Yahel can run"); } } Yahel inherits from Person and overrides the speak and run method according to requirements of the class. It just means that you give your own new implementation to the methods. Now whenever you create an instance of the Yahel and call those methods, it will give you the one that belong to Yahel class and not of Person class.

+1

Avinesh THANK YOU, you explained it very good 🙏🏼

0

u can use constructor

0

Avinash , thanks! but i dont understand what you wrote in the "Note:" ... explain please? and btw what is @Override ? i use it when i use interface but idk what its doing...