多态
来源:互联网 发布:网络教育统考在哪里考 编辑:程序博客网 时间:2024/06/08 16:30
/**
* 多态:编译时的类型和运行时的类型不一致,就可能出现多态
* Fruit f=new Apple(5);编译时引用f的类型是父类Fruit,运行时f的类型是子类Apple类型
*
* 1、f.put();首先put()方法必须是父类拥有的,当子类重写了这个方法,
* 通过f(父类Fruit)调用时该方法时调用的是子类重写了的put()方法,而不是父类的put()方法
*
* 这就是多态,通过父类的引用调用了子类的重写方法
*
* 2、f.show();//error 子类特有的方法不能通过父类引用调用
*
*/
public class TestDuoT {
public static void main(String[] args) {
Fruit f=new Apple(5);
System.out.println(f.weigth);//属性没有多态性
f.put();//
//f.show();//error
}
}
class Fruit{
public int weigth;
public void put(){
System.out.println("我是Sub水果");
}
}
class Apple extends Fruit{
public Apple(int weigth){
this.weigth=weigth;
}
public void put(){
System.out.println("我是子类Apple");
}
public void show(){
System.out.println("哈哈");
}
* 多态:编译时的类型和运行时的类型不一致,就可能出现多态
* Fruit f=new Apple(5);编译时引用f的类型是父类Fruit,运行时f的类型是子类Apple类型
*
* 1、f.put();首先put()方法必须是父类拥有的,当子类重写了这个方法,
* 通过f(父类Fruit)调用时该方法时调用的是子类重写了的put()方法,而不是父类的put()方法
*
* 这就是多态,通过父类的引用调用了子类的重写方法
*
* 2、f.show();//error 子类特有的方法不能通过父类引用调用
*
*/
public class TestDuoT {
public static void main(String[] args) {
Fruit f=new Apple(5);
System.out.println(f.weigth);//属性没有多态性
f.put();//
//f.show();//error
}
}
class Fruit{
public int weigth;
public void put(){
System.out.println("我是Sub水果");
}
}
class Apple extends Fruit{
public Apple(int weigth){
this.weigth=weigth;
}
public void put(){
System.out.println("我是子类Apple");
}
public void show(){
System.out.println("哈哈");
}
}
在java中运行的结果是:5
我是子类Apple
0 0
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- hdu5372 Segment Game (树状数组)
- 【Android】BroadcastReceiver的生命周期
- understanding the Euler Lagrange equation
- c++中map与unordered_map的区别
- LeetCode 226. Invert Binary Tree
- 多态
- (java)Rotate Image
- 【Android】Intent过滤器
- hive comand
- cannot open GHOSTERR.TXT
- LINUX操作系统如何启动HTTPD服务
- 【Android】多媒体编程——MediaPlayer音频播放
- jar包的解压、压缩
- Processes and Memory Organisation