java ⼦类继承⽗类重写tostring 和重写equals ⽅法
⽤学⽣的输出为例⼦,⼦⽗类,然后在⼦类中新定义⼀个属性并可以给⽗类属性赋值,以及重写tostring和重写equals⽅法。demo测试
⽗类定义属性
⼦类定义新属性,重写函数package Student ;public class demo { public static void main (String [] args ) { // TODO Auto-generated method stub Undergraduate s1 = new Undergraduate ("张三", 30, "专科"); Undergraduate s2 = new Undergraduate ("张三", 30, "本科"); Undergraduate s3 = new Undergraduate ("张三", 30, "本科"); System .out .println (s1.equals (s2)); System .out .println (s3.equals (s2)); System .out .println (s1); System .out .println (s2); System .out .println (s3); }}
1
2
3
4
5
6
7
8
9
10
java的tostring方法11
12
13
14
15
16
17
18
19
20
21package Student ;public class Student { public String name ; public int age ; public Student () { // TODO Auto-generated constructor stub } public Student (String name , int age ) { this .name = name ; this .age = age ; } public void show () { System .out .println (name + "," + age ); }}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
运⾏结果展⽰package Student ;public class Undergraduate extends Student { public String degr
re ; public Undergraduate (String name , int age , String degrre ) { super (name , age ); this .degrre = degrre ; } @Override public int hashCode () { final int prime = 31; int result = 1; result = prime * result + ((degrre == null ) ? 0 : degrre .hashCode ()); return result ; } @Override public boolean equals (Object obj ) { if (this == obj ) return true ; if (obj == null ) return false ; if (getClass () != obj .getClass ()) return false ; Undergraduate other = (Undergraduate ) obj ; if (degrre == null ) { if (other .degrre != null ) return false ; } else if (!degrre .equals (other .degrre )) return false ; return true ; } @Override public String toString () { return "degrre=" + degrre + ", name=" + name + ", age=" + age + ""; } public void show () { System .out .println (name + "," + degrre + "," + age ); }}
123456789101112131415161718192021222324252627282930313233343536373839404142434445
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论