[问题] 练习遇到有关继承、接口、抽象类别的问题

楼主: s9209122222 (海海海)   2015-09-26 16:39:00
最近读到了接口,所以创了一个名叫Phone 的抽象类别、两个分别叫SurfInternet
和Chat的接口,但编译过程一直出现错误,说非static的方法不能被static的东西给关
联,但我就是没看到有东西被我用成static啊!拜托各位帮帮我。
interface SurfInternet
{
void SurfInternet(String WebName);
}
interface Chat
{
void Chat(String ToWhom);
}
abstract class Phone
{
int price;
abstract void expensive();
void PrintPrice()
{
System.out.println("Price="+price);
}
}
class Sony extends Phone implements SurfInternet,Chat
{
public Sony(int price,String WebName,String ToWhom)
{
this.price=price;SurfInternet(WebName);Chat(ToWhom);
}
public void Chat(String ToWhom)
{
System.out.println("Talking to "+ToWhom);
}
public void SurfInternet(String WebName)
{
System.out.println("Surfing "+WebName);
}
public void expensive()
{
System.out.println("It is so expensive!");
}
}
public class Test
{
public static void main(String[] args)
{
Sony sony=new Sony(10000,"yahoo","John");
Sony.expensive();
}
}
结果:
Test.java:42: error: non-static method expensive() cannot be referenced from a static context
Sony.expensive();
^
1 error
到底~~~﹍﹍
不知道我有没有理解错,接口比抽象类别还要更抽象简洁,抽象类别是给和自己有关连的东西继承的,
而接口只是要给他多个功能用而已。然后还是搞不懂这两个东西到底有什么实际用途,就算没有这两个东西
好像也不会怎样,难道他们只是用来定义东西的吗?
作者: luckyshin (大屁)   2015-09-26 16:57:00
Sony要改成sony
楼主: s9209122222 (海海海)   2015-09-26 17:00:00
您真是太神了!眼睛看到脱窗没发现
作者: luckyshin (大屁)   2015-09-26 17:21:00
跟Polymorphism有关, 然后也可以拿来实现多重继承
作者: LPH66 (-6.2598534e+18f)   2015-09-26 17:48:00
当某个函式需要一个物件有某个函式时宣告“我收一个有某函式的物件”这件事即是靠 interface以 IArea 跟 Circle 的例子, 一个函式宣告它收 IArea 物件即表示它期望传进来的物件有 area() 函式可以用那当你不只有 Circle 实作 IArea 时, 其他实作的 class的物件也能交给目标函式使用这就是 interface 这东西的精神: "物件要提供的接口"(这也是为什么它会叫做 interface 接口的原因)接口跟抽象类别的差别在于接口只宣告我要有什么接口抽象类别除接口外可能提供某几个接口有默认行为
楼主: s9209122222 (海海海)   2015-09-26 17:54:00
好像有点了解了,感谢那各位在写程式的时候都是先定好interface后再写其他的吗?
作者: ah7675 (阿毛)   2015-09-27 16:56:00
interface == abstract class without properties

Links booklink

Contact Us: admin [ a t ] ucptt.com