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

28th May 2020, 10:01 AM
Yahel
Yahel - avatar
5 odpowiedzi
+ 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
28th May 2020, 10:27 AM
Avinesh
Avinesh - avatar
+ 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.
28th May 2020, 11:18 AM
Avinesh
Avinesh - avatar
+ 1
Avinesh THANK YOU, you explained it very good 🙏🏼
28th May 2020, 11:22 AM
Yahel
Yahel - avatar
0
u can use constructor
28th May 2020, 10:22 AM
durian
durian - avatar
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...
28th May 2020, 10:35 AM
Yahel
Yahel - avatar