1. 子类覆盖了父类的方法和具有同名的属性
package com.sun.util; import java.math.BigDecimal; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Scanner; class A{ public int a=1; public int b=2; public void add(){ System.out.println("A add"); } public void minus(){ System.out.println("A minus"); } } public class B extends A{ public int a=3; public int b=4; public int c=5; @Override public void add() { // TODO Auto-generated method stub // super.add(); System.out.println("B add"); } public void multi(){ System.out.println("B multi"); } public static void main(String[] args) { LinkedList<Integer> list=new LinkedList<>(); list.add(1, 1); A a = new B(); System.out.println(a.a); //1 System.out.println(a.b); //2 a.add(); a.minus(); // a.multi() ;// 无法访问子类的新增方法 B b =new B(); System.out.println(b.a); //3 System.out.println(b.b); //4 System.out.println(b.c); b.add(); } }
1
2
B add
A minus
3
4
5
B add
1. 子类覆盖了父类的方法和没有同名的属性
package com.sun.util; import java.math.BigDecimal; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Scanner; class A{ public int a=1; public int b=2; public void add(){ System.out.println("A add"); } public void minus(){ System.out.println("A minus"); } } public class B extends A{ // public int a=3; // public int b=4; public int c=5; @Override public void add() { // TODO Auto-generated method stub // super.add(); System.out.println("B add"); } public void multi(){ System.out.println("B multi"); } public static void main(String[] args) { A a = new B(); System.out.println(a.a); //1 System.out.println(a.b); //2 a.add(); a.minus(); // a.multi() ;// 无法访问子类的新增方法 B b =new B(); System.out.println(b.a); //1 System.out.println(b.b); //2 System.out.println(b.c); b.add(); } }
1
2
B add
A minus
1
2
5
B add