java中的重载与重写的理解
1.重载必须在同一各类中吗?
Overloading in Java can occur when two or more methods in the same class share the same name
or even if a child class shares a method with the same name as one of it’s parent classes.
2.重写必须在不同类中吗?
public class Test{
public static void main(String[] args){
System.out.println(new Test());
System.out.println(new Test(){
public String toString(){
return "manual override";
}
});
System.out.println(new Test(){
public String gm(){
return "manual gm";
}
}.gm());
} //end of main method
public String gm(){
return "gm";
}
}
----------------解决方案--------------------------------------------------------
重载:
非继承的类关系需要在同一个中写方法重载吧,因为在不同的类中虽然方法名,参数一样,但是可以用不同的类对象加以区分的。
如果是继承的关系,可以在子类中重载父类的方法。
重写:
需要在不同的类中写,而且类关系应该是继承,得用override声明要重写的方法。在同一个类中不能重写,并且也没有意义。
----------------解决方案--------------------------------------------------------