2014-11-05 123 views
0

我在调试此代码时遇到困难。我已经尝试了很多替代方法来摆脱错误,但由于我不熟悉Java,所以似乎无法指出发生了什么问题。错误:类不抽象,也不覆盖抽象方法

public abstract class Animal { 

    private String name;  
    private String type; 

    public Animal(String name, String type) {  
     this.name = name; 
     this.type = type;  
    }  

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

    public String getType() {   
     return this.type;  
    }   

    public abstract void speak(); 

} 



public class Dog extends Animal{ 


    public String getName() { 
     return super.getName();  } 

    public String getType() {  
     return super.getType(); } 

    public void speak(String name, String type){ 
     System.out.println("arf!");  } 

    } 


public class Ark{ 
    static void main(String[] args){ 

     Dog cookie = new Dog();   
     cookie.speak(); 

    } 
} 

谢谢!

+1

能否请您发表您的错误? – fxm 2014-11-05 16:25:12

+1

严重的是,不要像这样缩进你的代码!将右括号放在下一行! – vefthym 2014-11-05 16:28:39

回答

2
public abstract void speak(); 

您需要实现这Dog

您已经实现

public void speak(String name, String type) 
{ System.out.println("arf!"); } 

因此Dog是抽象的,但你并没有指明是什么,你niether实施speak()不带参数。删除参数,反正你没有使用它们。

@Override 
public void speak() 
{ System.out.println("arf!"); } 
+0

嗨,非常感谢你的回复!删除参数,现在的错误信息是“构造函数Animal类中的Animal不能应用于给定类型; public class Dog extends Animal {” – Aly 2014-11-05 16:42:00

+0

动物类具有参数化构造函数,所以当Dog类扩展它时,编译器插入super()(没有参数),它调用你没有的超类(动物)的默认构造函数,因此错误 – 2014-11-05 16:45:54

+0

一个解决方案是为Dog创建参数化构造函数。 ** public Dog(String name,String type){ super(name,type); } ** – 2014-11-05 16:50:05

0

抽象说话方法没有与您实施的Dog.speak(字符串字符串)具有相同的参数。

0

你需要重写speak方法在狗类,将其更改为

public void speak() 
{ 
    System.out.println("arf!"); 
} 
0
public abstract class Animal { 

    private String name;  
    private String type; 

    public Animal(String name, String type) {  
     this.name = name; 
     this.type = type; }  

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

    public String getType() {  
     return this.type; }  

    public abstract void speak(String name, String type);  
// if you want parameters in the Dog class for this method you must include them here otherwise it wont work 
} 



public class Dog extends Animal{ 


    public String getName() { 
     return super.getName();  } 

    public String getType() {  
     return super.getType(); } 

    public void speak(String name, String type){ 
     System.out.println("arf!");  } 

} 
相关问题