成员变量没有多态,方法才有多态

/**
 * @author 031202
 *
 * TODO To change the template for this generated type comment go to Window -
 * Preferences - Java - Code Style - Code Templates
 */
public class Test {
 public static void main(String[] args) {
  Base b = new Subclass();
  System.out.println(b.x);
  System.out.println(b.method());
 }
}

class Base {
 int x = 2;

 int method() {
  return x;
 }
}

class Subclass extends Base {
 int x = 3;

 int method() {
  return x;
 }
}

Answer:
2
3

你可能感兴趣的:(templates,class,string,java,go,java基础)