标签:animal 重写 col html cte 父类 print 成员 str
Java覆盖和隐藏
Java里用final修饰的成员和成员变量能否被继承
/**
* Cat class
* Java 中实例方法被覆盖,静态方法被隐藏
*
* @author libin
* @date 2019/1/28 17:05
*/
class Animal {
public static void testClassMethod() {
System.out.println("Class" + " method in Animal.");
}
public void testInstanceMethod() {
System.out.println("Instance " + " method in Animal.");
}
}
public class Cat extends Animal {
public static void testClassMethod() {
System.out.println("The class method" + " in Cat.");
}
@Override
public void testInstanceMethod() {
System.out.println("The instance method" + " in Cat.");
}
public static void main(String[] args) {
Cat myCat = new Cat();
Animal myAnimal = myCat;
Animal.testClassMethod();
myAnimal.testInstanceMethod();
}
}
参考答案
Class method in Animal.
The instance method in Cat.
/**
* Demo class
*
* @author libin
* @date 2019/1/28 16:25
*/
class A {
static void fun() {
System.out.println("A.fun()");
}
}
class B extends A {
static void fun() {
System.out.println("B.fun()");
}
}
public class Demo {
public static void main(String args[]) {
A a = new B();
a.fun();
}
}
参考答案
A.fun()
/**
* Son class
*
* @author libin
* @date 2019/1/29 10:25
*/
class Dad {
protected static String me = "dad";
public void printMe() {
System.out.println(me);
}
}
public class Son extends Dad {
protected static String me = "son";
@Override
public void printMe() {
System.out.println(me);
}
public static void main(String[] args) {
Dad dad = new Son();
Son son = new Son();
System.out.println("son.me:" + son.me);
System.out.println("dad.me:" + dad.me);
System.out.println("Son.me:" + Son.me);
System.out.println("Dad.me:" + Dad.me);
son.printMe(); // dad
dad.printMe(); // dad
}
}
参考答案
son.me:son
dad.me:dad
Son.me:son
Dad.me:dad
son
son
反编译Class代码
class Dad
{
protected static String me;
public void printMe() {
System.out.println(Dad.me);
}
static {
Dad.me = "dad";
}
}
public class Son extends Dad
{
protected static String me;
@Override
public void printMe() {
System.out.println(Son.me);
}
public static void main(final String[] args) {
final Dad dad = new Son();
final Son son = new Son();
System.out.println("son.me:" + Son.me);
System.out.println("dad.me:" + Dad.me);
System.out.println("Son.me:" + Son.me);
System.out.println("Dad.me:" + Dad.me);
son.printMe();
dad.printMe();
}
static {
Son.me = "son";
}
}
参考链接
标签:animal 重写 col html cte 父类 print 成员 str
原文地址:https://www.cnblogs.com/hglibin/p/10333551.html