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 在彈出框中可以直接輸入要繼承的父類的名字如下圖: