class Cat{
protected String color = "random";
public Cat(){}
public void showCatColor(){
System.out.println("cat:"+color);
}
public void showColor(){
System.out.println("cat:"+color);
}
}
public class WhiltCat extends Cat{
protected String color = "white";
public WhiltCat(){
super();
}
public void showCatColor(){
System.out.println("WhiltCat:"+color);
}
public void showColor(){
System.out.println("WhiltCat:"+color);
}
public static void main(String[] args){
WhiltCat whiltCat = new WhiltCat();
Cat cat =whiltCat;
cat.showColor();
cat.showCatColor();
}
}
运行结果:
WhiltCat:white
WhiltCat:white
/*总结:WhiltCat whiltCat = new WhiltCat();
Cat cat =whiltCat;//对象上转型
子类WhiltCat被实例化了所有非静态成员变量被加载并且实例化;
static修饰的变量和方法随类的加载而初始化和加载
Cat父类没有初始化但加载了所以静态(static修饰的)被加载了。
所以会调用父类的 同名方法,不会调用子类的。
所以当 子类重写父类的同名静态方法时
Cat cat = new WhiltCat();
cat会调用自己的(只要父类自己有就不会调用子类的)
*/
package com.interview.demo;
class Cat{
protected static String color = "random";
public Cat(){}
public void showCatColor(){
System.out.println("cat:"+color);
}
public static void showColor(){
System.out.println("cat:"+color);
}
}
public class WhiltCat extends Cat{
protected static String color = "white";
public WhiltCat(){
super();
}
public void showCatColor(){
System.out.println("WhiltCat:"+color);
}
public static void showColor(){
System.out.println("WhiltCat:"+color);
}
public static void main(String[] args){
WhiltCat whiltCat = new WhiltCat();
Cat cat =whiltCat;
cat.showColor();
cat.showCatColor();
}
}
运行结果:
cat:random
WhiltCat:white
***********************************************
package com.interview.demo;
class Cat{
protected static String color = "random";
public Cat(){}
public void showCatColor(){
System.out.println("cat:"+color);
}
public static void showColor(){
System.out.println("cat:"+color);
}
}
public class WhiltCat extends Cat{
protected static String color = "white";
public WhiltCat(){
super();
}
public void showCatColor(){
System.out.println("WhiltCat:"+color);
}
public static void showColor(){
System.out.println("WhiltCat:"+color);
}
public static void main(String[] args){
/*Cat cat = new Cat();
WhiltCat whiltCat = (WhiltCat)cat;
cat.showColor();
cat.showCatColor();
//运行结果:Exception in thread "main" java.lang.ClassCastException
*/
/*Cat cat = new WhiltCat();
WhiltCat whiltCat = (WhiltCat)cat;
cat.showColor();
cat.showCatColor();
//运行结果:cat:random WhiltCat:white(父类有的不会用子类的)
*/
/*Cat cat = new WhiltCat();
WhiltCat whiltCat = (WhiltCat)cat;
whiltCat.showColor();
whiltCat.showCatColor();
//运行结果WhiltCat:white WhiltCat:white
*/
}
}