在java中,类的继承需要用到关键字extends:
如下面的代码:
package javaapplication9;
/**
*
* @author Lamorh
*/
class Person
{
int age;
String name;
int avoirdupois;
public void eat()
{
System.out.println("People eat");
}
public void sleep()
{
System.out.println("People sleep");
}
}
public class JavaApplication9 extends Person{
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
JavaApplication9 text=new JavaApplication9();
text.eat();
text.sleep();
}
}
运行结果:
子类可以继承父类的东西,
但子类有时也需要增加一些自己的特性,
而这个就靠关键字:super
如:
package javaapplication9;
/**
*
* @author Lamorh
*/
class Person
{
int age;
String name;
int avoirdupois;
public void eat()
{
System.out.println("People eat");
}
public void sleep()
{
System.out.println("People sleep");
}
}
public class JavaApplication9 extends Person{
/**
* @param args the command line arguments
*/
public void eat()
{
super.eat();
System.out.println("Worker eat");
}
public static void main(String[] args) {
// TODO code application logic here
JavaApplication9 text=new JavaApplication9();
text.eat();
text.sleep();
}
}
运行结果:
当然,有时候子类也需要改变父类的一些特性,于是就需要
进行函数的修改,于是只需要重写该函数即可。
函数的重载:
package calculate;
/**
*
* @author Lamorh
*/
public class Calculate {
/**
* @param args the command line arguments
*/
final float PI=3.1415926f;
public float GetArea(float r)
{
return PI*r*r;
}
public float GetArea(float l,float w)
{
return l*w;
}
public static void main(String[] args) {
// TODO code application logic here
Calculate cal=new Calculate();
float l=10.0f;
float w=20.0f;
float areaRectangle=cal.GetArea(l, w);
System.out.println("长为:"+l+" 宽为:"+w+"的矩形的面积为:"+areaRectangle);
float r=8.0f;
float areaCire=cal.GetArea(r);
System.out.println("半径为:"+r+" 的圆的面积为:"+areaCire);
}
}
运行结果: