java继承 、方法重写、重写toString方法

1.Java的继承,关键词Extends

 1 package cn.mwf.oo;
 2 
 3 public class TextExtends {
 4     public static void main(String[] args) {
 5         Student s = new Student("侠客小飞", 60, "计算机科学与技术");
 6         s.rest();
 7         s.study();
 8     }
 9 
10 }
11 class Person{
12     String name;
13     int height;
14     public void rest() {
15         System.out.println("休息一会!");
16     }
17 }
18 class Student extends Person{
19     String major;//专业
20     public void study() {
21         System.out.println("在图书管学习java!");
22     }
23     public Student(String name,int height,String major) {
24         this.name = name;
25         this.height = height;
26         this.major = major;
27     }
28 }

2.方法的重写

 1 package cn.mwf.oo;
 2 //方法的重写
 3 public class TestOverride {
 4     public static void main(String[] args) {
 5         Vehicle v1 = new Vehicle();
 6         v1.run();
 7         v1.stop();
 8         Vehicle v2 = new Hourse();
 9         v2.run();
10         v2.stop();
11         Vehicle v3 = new Airplane();
12         v3.run();
13         v3.stop();
14     }
15 }
16 //Vehicle类
17 class Vehicle{
18     public void run() {
19         System.out.println("跑···");
20     }
21     public void stop() {
22         System.out.println("停止···");
23     }
24 }
25 //Hourse类继承Vehicle类
26 class Hourse extends Vehicle{
27     public void run() {
28         System.out.println("嘚嘚嘚的跑");
29     }
30 }
31 //Airplane类继承Vehicle类
32 class Airplane extends Vehicle{
33     public void run() {
34         System.out.println("在空中飞");
35     }
36     public void stop() {
37         System.out.println("在空中不能停,会掉下来");
38     }
39 }

3.重写toString方法

 1 package cn.mwf.oo;
 2 
 3 public class TestObject {
 4     public static void main(String[] args) {
 5         TestObject to = new TestObject();
 6         System.out.println(to.toString());
 7         
 8         Person2 p2 = new Person2("茜茜",6);
 9         System.out.println(p2.toString());
10     }
11     public String toString() {
12         return "测试Object对象";
13     }
14 }
15 class Person2{
16     String name;
17     int age;
18     
19     public String toString() {
20         return name+",年龄:"+age;
21     }
22     public Person2(String name, int age) {
23         this.name = name;
24         this.age = age;
25     }
26 }

猜你喜欢

转载自www.cnblogs.com/ma1998/p/11535874.html