日期:2014-05-20 浏览次数:20843 次
package chapter4; class MostCommonDiv{ private int m; private int n; public int f(int a, int b){ this.m = a; this.n = b; if(m<n){ int temp = 0; temp = m; m = n; n = temp; } int start = n; int div = 0; for(int i=start; i>0; i--){ if((m%i == 0) && (n%i == 0)){ div = i; break; } } return div; } } class SubMostCommonDiv extends MostCommonDiv{ protected static int resultOfSupper = 0; public int f(int a, int b){ int m = super.f(a, b); this.resultOfSupper = (a*b)/m; if(a<b){ int temp = 0; temp = a; a = b; b = temp; } int start = a; int subdiv = 0; while(start > 0){ if((start%a == 0) && (start%b ==0)){ subdiv = start; break; }else{ start ++; } } return subdiv; } } public class Exam4_18 { public static void main(String[] args) { MostCommonDiv test1 = new MostCommonDiv(); SubMostCommonDiv test2 = new SubMostCommonDiv(); int a = 32; int b = 8; System.out.println("f function in father:"+test1.f(a, b)); System.out.println("f function in son:"+((SubMostCommonDiv)test1).f(a, b)); System.out.println("add the result of (a*b)/m="+SubMostCommonDiv.resultOfSupper); System.out.println("f function in son:"+test2.f(a, b)); System.out.println("add the result of (a*b)/m="+test2.resultOfSupper); } }
public class Exam4_18 { public static void main(String[] args) { MostCommonDiv test1 = new SubMostCommonDiv(); SubMostCommonDiv test2 = new SubMostCommonDiv(); int a = 32; int b = 8; System.out.println("f function in father:"+test1.f(a, b)); System.out.println("f function in son:"+((SubMostCommonDiv)test1).f(a, b)); System.out.println("add the result of (a*b)/m="+SubMostCommonDiv.resultOfSupper); System.out.println("f function in son:"+test2.f(a, b)); System.out.println("add the result of (a*b)/m="+test2.resultOfSupper); } }
------解决方案--------------------
MostCommonDiv test1 = new MostCommonDiv();
test1 声明的是父类, 实现的是父类, 这样是不能强转成子类的.
只有多态的方式下,才能向下转型呢.
比如:
MostCommonDiv test3=new SubMostCommonDiv();
这样可以用(SubMostCommonDiv)test3.
(但多态的情况下,自然调用的方法是子类覆写了的父类方法. 也不需要转型了.
只有调用子类新加的方法,才需要用向下转型后去调用.)
------解决方案--------------------
System.out.println("f function in son:"+((SubMostCommonDiv)test1).f(a, b));
错误很明显,父类对象不能强转成子类的