您的位置:首页 > 编程语言 > Java开发

java 继承 重写

2015-07-02 16:03 756 查看
package inheritance.override;
/**
* 1、先开辟空间
* 2、再调用构造器
*    父类声明赋值
*    父类构造器
*    子类声明赋值
*    子类构造器
* 3、返回地址
*
* 属性: 就近原则
* 父类中的方法: 如果重写 -->找重写,没有重写 -->找父类   ,新增不可见
* @author Administrator
*
*/
public class Fruit {
String type ="fruit";

public Fruit() {
System.out.println(this.type +"-->"+this.getType()); //fruit null
//this.test(); //新增不可见
}
public String getType() {
return type;
}

public void setType(String type) {
this.type = type;
}

public static void main(String[] args) {
new Apple();
}
}

class Apple  extends Fruit{
String type ="Apple";

public Apple() {
System.out.println(this.type +"-->"+this.getType()); //Apple -->Apple
}
public String getType() {
return type;
}

public void setType(String type) {
this.type = type;
}

public void test(){
System.out.println("new add");
}
}


package inheritance.override;

public class Servlet {

public Servlet() {

this.service();

}

public void service(){

this.doGet();

this.doPost();

}
public void doGet(){

}
public void doPost(){

}
public static void main(String[] args) {
new HttpServlet();
//1、开辟空间
//2、调用构造器  Servlet() HttpServlet()
//3、返回地址
}


}

class HttpServlet extends Servlet{

public HttpServlet() {

//默认查找父类的无参构造 super()

}

public void doGet(){

System.out.println(“httpservlet doGet”);

}

public void doPost(){

System.out.println(“httpservlet doPost”);

}

}

package inheritance.override;
/**
* 先编译后运行:
* 编译:从代码所属的当前类中向上找Object  +就近最优
* 运行:在编译基础上,从对象从属类中向上找 Object
*
*
* @author Administrator
*
*/
public class Father {
public void print(){
test('a');  //编译:test(char) -->test(int)  运行从该对象查找
}

public void test(int a){
System.out.println("2 Father test(int)");
}
//重写类的方法签名不能变  签名: test(char)
public  void test(char a){
System.out.println("1 Father test(char)");
}

public static void main(String[] args) {
new Son().print();
}
}

class Son extends Father{
/*
*重写了父类的方法优先调用,没有重写父类的方法那就调用父类的方法。
* @see inheritance.override.Father#test(char)
*/
public  void test(char a){
System.out.println("3 son test(char)");
}

public void test(int a){
System.out.println("4 Son test(int)");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: