这篇文章主要讲解了如何使用Java中的继承,多态,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。
继承:
class Person{ String gender="unknown";//为了测试继承,先赋值 int age; String family_address; private String children; } class Student extends Person{ } public class Demo { public static void main(String[] args) { Student st=new Student(); System.out.println(st.gender);//unknown // System.out.println(st.children);//报错,children是父类私有 } }
class Person{ String gender="unknown";//为了测试继承,先赋值 int age; String family_address; private String children; Person(){ System.out.println("为了测试默认有super()"); } } class Student extends Person{ } public class Demo { public static void main(String[] args) { Student st=new Student(); } } -------------------结果: 为了测试默认有super()
class Person{ String gender; int age; String family_address; private String children; Person(String gender,int age,String family_address){ this.gender=gender; this.age=age; this.family_address=family_address; } } class Student extends Person{ Student(String gender,int age,String family_address){ super(gender,age,family_address); } } public class Demo { public static void main(String[] args) { Student st=new Student("男",18,"M78星云"); System.out.println(st.gender+st.family_address);//男M78星云 } }
package 重写; class Person{ void show() { System.out.println("run in Fu"); } } class Student extends Person{ void show() { System.out.println("override in Zi"); super.show(); } } public class Demo { public static void main(String[] args) { Student st=new Student(); st.show(); //结果:override in Zi //run in Fu } }
package 多态_usage; class Animal{ int age=4; void show() { System.out.println("run in Fu"); } } class Tiger extends Animal{ int age=6; void show() { System.out.println("ao ao ao"); } } class Cat extends Animal{ void show() { System.out.println("miao miao miao"); } } public class Demo2{ public static void main(String args[]) { Animal a=new Tiger();//把老虎转型成父类-动物 Animal b=new Cat(); System.out.println(a.age);//4 a.show();//run in Zi b.show();//miao miao miao } }
成员变量子父类同名时,成员变量的调用看“.”所属的对象的类。比如是父类.成员变量那么就是父类的。
看完上述内容,是不是对如何使用Java中的继承,多态有进一步的了解,如果还想学习更多内容,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。