0
Help me to fix the problem??
public class Dog { public int legs; public void bar() { System.out.println("hiii"); } public class Cat extends Dog { Dog() { legs = 3; } } } public class Program { public static void main(String[] args) { Cat a = new Cat(); a.bar(); } }
5 Réponses
+ 3
Shaik.Shahir
Many mistakes
If you create class inside another class then it would be inner class and inner class cannot extend outer class because inner class is already inside outer class so create Cat class separately.
2nd mistake you have created a method Dog inside Cat class which is wrong, that would be constructor of Cat class.
Remember method should have return type and constructor doesn't.
+ 3
I got it
Thanks!
+ 2
Shaik.Shahir
Many mistakes
If you create class inside another class then it would be inner class and inner class cannot extend outer class because inner class is already inside outer class so create Cat class separately.
2nd mistake you have created a method Dog inside Cat class which is wrong, that would be constructor of Cat class.
Remember method should have return type and constructor doesn't.
+ 1
It is better to move the Cat class out of the Dog class as a separate class and rename its constructor Dog () to Cat (), because it is a Cat class
+ 1
Shaik.Shahir
One more thing Cat and Dog both are from same family means both are animals and both have different behaviour, Dog bark and Cat meow so Dog cannot be super class of Cat. Animal can be super class of both Dog and Cat. So it should be like this:
public class Program
{
public static void main(String[] args) {
Dog d = new Dog ();
d.bark();
d.legs();
Cat c = new Cat ();
c.meow();
c.legs();
}
}
class Animal {
public int legs;
public Animal () {
legs = 4;
}
public void legs() {
System.out.println ("Legs " + legs);
}
}
class Dog extends Animal {
public void bark() {
System.out.println ("Bark");
}
}
class Cat extends Animal {
public void meow() {
System.out.println ("Meow");
}
}