Search code examples
javamethodspolymorphismsubclasssuperclass

Confused about error while learning Polymorphism


I'm learning polymorphism and I am getting this red line in my superclass and sublcass it's commented on my code:

    public class Animals {
  private String name;

  public Animals(String name) {
      this.name = name;
        }

  public void changeName(String name){
      this.name= name;
  }

  public String getName(){
      return this.name;  // 
  }

}

here is my subclass:

public class Dog extends Animals {
    private String colour;

    public Dog(String name, String colour){
        super(name);  
        this.colour = colour;
    }

    public void changeColour(String colour) {
        this.colour = colour;
    }
    public String getColour(){
        return this.colour;
    }

}    

Here is the other script with the main method:

public class AnimalPolyTesting {
    public static void main(String[] args) {
        Animals puppy = new Dog("homie", "black"); // constructor Dog cannot be applied to given types;
        puppy.getName();
        (Dog) puppy.getColour(); // not a statement

    }
}

I'm not sure why I'm getting these red lines Edit: The code runs but nothing comes out. Edit2: Fixed the classes.


Solution

  • Your animals class should look like this

    public class Animals {
        private String name;
    
        public Animals(String name) {
            this.name = name;
        }
    
        public void changeName(String name){
            this.name= name;
        }
    
        public String getName(){
            return this.name;
        }
    
    }
    

    The problem you have is that your constructor had a void return type. Constructors should not have a return type. Secondly, your getName() method had a return type of void. To get it to work properly you need to declare what it's returning. Given this, I would leave it to you to implement the rest of your code.