1. java程序继承
packageextend;
/**
*圆类
*@author枫雅
*2019年3月21日
*/
publicclassCircle{
privatedoubler;
publicfinalstaticdoublePI=3.14;
publicCircle(doubler){
this.r=r;
}
publicdoubleCircumference(doubler){
return2*PI*r;
}
publicdoubleArea(doubler){
returnPI*r*r;
}
}
packageextend;
/**
*圆柱类,继承自圆类
*@author枫雅
*2019年3月21日
*/
{
privatedoubleh;
publicCylinder(doubler,doubleh){
super(r);
this.h=h;
}
publicdoubleCeArea(doubler,doubleh){
returnsuper.Circumference(r)*h;
}
publicdoubleVolume(doubler,doubleh){
returnsuper.Area(r)*h;
}
}
packageextend;
/**
*圆锥类,继承自圆柱类
*@author枫雅
*2019年3月21日
*/
{
publicCone(doubler,doubleh){
super(r,h);
}
publicdoubleCeArea(doubler,doubleh){
returnsuper.CeArea(r,h)/2;
}
publicdoubleVolume(doubler,doubleh){
returnsuper.Volume(r,h)/3;
}
}
packageextend;
/**
*测试类
*@author枫雅
*2019年3月21日
*/
publicclassTest{
publicstaticvoidmain(String[]args){
doubler=3;
doubleh=2;
Circlecircle=newCircle(r);
System.out.println("半径为:"+r+"圆的周长为:"+circle.Circumference(r));
System.out.println("半径为:"+r+"圆的面积为:"+circle.Area(r));
Cylindercylinder=newCylinder(3,2);
System.out.println("底部半径为:"+r+",高为:"+h+"圆柱的侧面积为:"+cylinder.CeArea(r,h));
System.out.println("底部半径为:"+r+",高为:"+h+"圆柱的体积为:"+cylinder.Volume(r,h));
Conecone=newCone(3,2);
System.out.println("底部半径为:"+r+",高为:"+h+"圆锥的侧面积为:"+cone.CeArea(r,h));
System.out.println("底部半径为:"+r+",高为:"+h+"圆锥的体积为:"+cone.Volume(r,h));
}
}
2. java编程:(二)类的继承
public class DogTest {
public static void main(String[] args) {
Dog dog = new Dog("Mimi ", "3");
dog.setNickname("Baby");
System.out.println(dog.name + "is" + dog.age + " years old");
System.out.println("It’s nickname is " + dog.getNickname());
Animal animal = new Animal("Tom ", "3");
System.out.println(animal.name + animal.run());
}
}
/**
*
*/
package test;
/**
* @author lilin
*
*/
public class Dog extends Animal {
public Dog(String name, String age) {
super(name, age);
}
private String nickname;
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String run() {
System.out.println("run by four feet");
return null;
}
}
/**
*
*/
package test;
/**
* @author lilin
*
*/
public class Animal {
protected String name;
protected String age;
public Animal(String name, String age) {
this.name = name;
this.age = age;
}
public String run() {
return "can run";
}
}
3. eclipse java中如何继承一个类
继承一个类用关键字 extends 就行了 ,
举个例子: 类A继承类B 那么java代码就是:
publicclassAextendsB{
}
或者你新建类的时候:
file -- new -- class 在弹出框中可以直接输入要继承的父类的名字如下图: