本文實例講述了java方法重寫,分享給大家供大家參考。具體分析如下:
一、方法的重寫概述:
1、在子類中可以根據需要對從基類中繼承來的方法進行重寫。
2、重寫的方法和被重寫的方法必須具有相同方法名稱、參數列表和返回類型。
3、重寫方法不能使用比被重寫的方法更嚴格的訪問權限。
二、程序代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
class Person{ private int age; private String name; public void setAge( int age){ this .age = age; } public void setName(String name){ this .name = name; } public int getAge(){ return age; } public String getName(){ return name; } public String getInfo(){ return "Name is:" +name+ ",Age is " +age; } } class Student extends Person{ private String school; public void setSchool(String school){ this .school = school; } public String getSchool(){ return school; } public String getInfo(){ return "Name is:" +getName()+ ",Age is " +getAge()+ ",School is:" +school; } } public class TestOverRide{ public static void main (String args[]){ Student student = new Student(); Person person = new Person(); person.setAge( 1000 ); person.setName( "lili" ); student.setAge( 23 ); student.setName( "vic" ); student.setSchool( "shnu" ); System.out.println(person.getInfo()); System.out.println(student.getInfo()); } } |
執(zhí)行結果如下圖所示:
希望本文所述對大家的Java程序設計有所幫助。