/**
* @program: quartzLearn
* @description:
* @author: zyc
* @create: 2018-06-05 16:25
**/
package com.zjpavt.test.father;
import org.junit.Assert;
public class Father {
public static String print() {
System.out.println("father");
return "father";
}
private String a = "father a";
protected String b = "father b";
public String c = "father c";
public String getA() {
return a;
}
public String getB() {
return b;
}
public String getC() {
return c;
}
public String getSuperB() {
return b;
}
private String f() {
return "father f";
}
public static void main(String[] args) {
Father fs = new Son();
Father f1 = new Father();
Son s1 = new Son();
//直接调用成员看多态类型(代码中声明的对象类型), 在编译期运行,不涉及运行时多态
Assert.assertEquals(fs.b,f1.b);
Assert.assertEquals(fs.c,f1.c);
Assert.assertNotEquals(fs.b,s1.b);
Assert.assertNotEquals(fs.c,s1.c);
//调用成员方法看运行时类型
Assert.assertEquals(fs.getA(),s1.getA());
Assert.assertEquals(fs.getB(),s1.getB());
Assert.assertEquals(fs.getC(),s1.getC());
Assert.assertNotEquals(fs.getA(),f1.getA());
Assert.assertNotEquals(fs.getB(),f1.getB());
Assert.assertNotEquals(fs.getC(),f1.getC());
//静态方法看多态类型 与非静态方法一致(不推荐这种写法,静态方法使用类调用)
Assert.assertEquals(fs.print(),f1.print());
Assert.assertNotEquals(fs.print(),s1.print());
//私有的父亲成员方法,同名公开的子方法,不认为是覆盖
//实际过程中不会出现这种问题,私有方法根本访问不到
Assert.assertEquals(fs.f(),f1.f());
Assert.assertNotEquals(fs.f(),s1.f());
//通过super获取父对象成员
Assert.assertEquals(fs.getSuperB(),f1.getB());
}
}
/**
* @program: quartzLearn
* @description:
* @author: zyc
* @create: 2018-06-05 16:25
**/
package com.zjpavt.test.father;
public class Son extends Father {
/**
* Error:(36, 26) java: com.zjpavt.test.father.Son中的print()无法覆盖com.zjpavt.test.father.Father中的print()
返回类型java.lang.String与void不兼容
* 父子类中的同名同参静态方法必须具有相同的返回值
*/
/*public static String print() {
return "son";
}*/
public static String print() {
return "son";
}
private String a = "son a";
protected String b = "son b";
@Override
public String getA() {
return a;
}
@Override
public String getSuperB() {
return super.b;
}
@Override
public String getB() {
return b;
}
@Override
public String getC() {
return c;
}
public String f() {
return "son f";
}
public String c = "son c";
}