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

java继承

2014-11-03 17:33 337 查看
Java 是面向对象的编程语言,从上第一节编程课开始我们就天天听着老师唠叨着面向对象和面向过程的变成语言。其本质的不同就是面向对象的变成是将实物高度抽象化,自下先建立抽象模型然后再使用模型; 而面向过程的变成则是一种自顶向下的编程。既然面向对象的变成需要先建立高度抽象的模型,那么类就在期中扮演了一个非常重要的角色了。类(Class)实际上是对某种类型的对象定义变量和方法的原型,它表示对现实生活中一类具有共同特征的事物的抽象,是面向对象编程的基础。类是可以继承(extends)的,没有了继承可以说面向对象的编程就没法实现了。今天我就来学习一下java中继承(extends)的使用。

java中能够继承的两个类必须是之间存在实在的联系的。承是从已有的类中派生出新的类,新的类能吸收已有类的数据属性和行为,并能扩展新的能力。Java继承是使用已存在的类的定义作为基础建立新类的技术,新类的定义可以增加新的数据或新的功能,也可以用父类的功能,但不能选择性地继承父类。这种技术使得复用以前的代码非常容易,能够大大缩短开发周期,降低开发费用。比如可以分隔符先定义一个类叫车,车有以下属性:车体大小,颜色,方向盘,轮胎,而又由车这个类派生出轿车和卡车两个类,为轿车添加一个小后备箱,而为卡车添加一个大货箱。

package no8test;

public class ExtendsDemo
{
public static void main(String[] args)
{
dolly d=new dolly();
d.showCar();
truck t=new truck();
t.showCar();
}
}

class dolly extends car
{
private String myselfS="后备箱";
dolly()
{
super.setName("甲壳虫");
super.setColor("白色");
super.setLeght(2.5);
super.setWight(2);
super.setWheel(4);
}
protected  void showCar(){
super.showBase();
System.out.println(" 我有一个"+myselfS);
}

}

class truck extends car
{
private String myselfS="大货箱";
truck()
{
super.setName("解放牌皮卡");
super.setColor("绿色");
super.setWheel(6);
super.setLeght(4.5);
super.setWight(3);
}

protected  void showCar(){
super.showBase();
System.out.println(" 我有一个"+myselfS);
}

}

class car
{
private String Name;
private double leght;
private double  wight;
private String color;
private int wheel;

/**
* @return the Name
*/
public String getName()
{
return Name;
}

/**
* @param Name the Name to set
*/
public void setName(String Name)
{
this.Name = Name;
}

/**
* @return the leght
*/
public double getLeght()
{
return leght;
}

/**
* @param leght the leght to set
*/
public void setLeght(double leght)
{
this.leght = leght;
}

/**
* @return the wight
*/
public double getWight()
{
return wight;
}

/**
* @param wight the wight to set
*/
public void setWight(double wight)
{
this.wight = wight;
}

/**
* @return the color
*/
public String getColor()
{
return color;
}

/**
* @param color the color to set
*/
public void setColor(String color)
{
this.color = color;
}
protected void showBase(){
System.out.print("汽车名:"+this.Name+" 颜色:"+this.color+" 轮子"+getWheel()+"个 车长:"+this.leght+" 车宽:"+this.wight);
}

/**
* @return the wheel
*/
public int getWheel()
{
return wheel;
}

/**
* @param wheel the wheel to set
*/
public void setWheel(int wheel)
{
this.wheel = wheel;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息