導航:首頁 > 編程語言 > java繼承編程

java繼承編程

發布時間:2022-09-26 17:14:51

A. java編程的繼承屬性和構造方法的執行

new B();//執行過程如下:

  1. new,JVM為B類的對象分配內存

  2. 調用B的構造方法,執行初始化。

  3. B的構造方法自動調用父類的無參構造方法(編譯器會在子類的構造方法的第一行插入父類的無參構造方法)

  4. 父類A的構造方法中調用了方法setI(20);//此處是關鍵,new B();不會創建父類對象,調用父類構造方法只是用來執行父類中的初始化代碼,不是創建對象,創建對象是new關鍵字,構造方法只是初始化,這里可能很難理解,不過這是JVM執行的方式,也是new關鍵字的作用。

  5. 所以,父類A構造方法中調用的是子類的setI,不是父類的setI。整個過程中只有一個對象——B類的對象

B. 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));
}

}

C. java編程 繼承關系

/*
* 定義交通工具,汽車,火車,飛機這些類,注意它們的繼承關系,為這些類提供超出3個不同的構造器
*/
class Transport {

public Transport() {
}
}

class Bus extends Transport {

private String busName;

public Bus(String busName) {
this.busName = busName;
}
}

class Train extends Transport {

private String trainName;
private double trainSpeed;

public Train(String trainName, double trainSpeed) {
this.trainName = trainName;
this.trainSpeed = trainSpeed;
}
}

class Airplane extends Transport {

private String airplaneName;
private double airplaneSpeed;
private String Voyage;

public Airplane(String airplaneName, double airplaneSpeed, String Voyage) {
this.airplaneName = airplaneName;
this.airplaneSpeed = airplaneSpeed;
this.Voyage = Voyage;
}
}

D. 使用java繼承機制編程有什麼好處談談你的實踐體會

更安全。
繼承簡化了人們對事物的認識和描述,能清晰體現相關類間的層次結構關系。繼承提供了軟體復用功能。這種做法能減小代碼和數據的冗餘度,大大增加程序的重用性。提供多重繼承機制。出於安全性和可靠性的考慮,僅支持單重繼承,而通過使用介面機制來實現多重繼承。
Java是一門面向對象編程語言,不僅吸收了C++語言的各種優點,還摒棄了C++里難以理解的多繼承、指針等概念,因此Java語言具有功能強大和簡單易用兩個特徵。Java語言作為靜態面向對象編程語言的代表,極好地實現了面向對象理論,允許程序員以優雅的思維方式進行復雜的編程。

E. 求編寫一個Java類的繼承程序

java基礎,繼承類題目:編寫一個Java應用程序,該程序包括3個類:Monkey類、People類和主類 E

21.編寫一個Java應用程序,該程序包括3個類:Monkey類、People類和主類

E。要求:

(1) Monkey類中有個構造方法:Monkey (String s),並且有個public void speak()

方法,在speak方法中輸出「咿咿呀呀......」的信息。

(2)People類是Monkey類的子類,在People類中重寫方法speak(),在speak方法

中輸出「小樣的,不錯嘛!會說話了!」的信息。

(3)在People類中新增方法void think(),在think方法中輸出「別說話!認真思考!」

的信息。

(4)在主類E的main方法中創建Monkey與People類的對象類測試這2個類的功

能。、

復制代碼
package zhongqiuzuoye;

public class Monkey {

Monkey(String s) //構造
{}

public void speak()
{
System.out.println("咿咿呀呀......");
}
}

F. java繼承

繼承是面向對象編程技術的一塊基石,因為它允許創建分等級層次的類。運用繼承,你能夠創建一個通用類,它定義了一系列相關項目的一般特性。該類可以被更具體的類繼承,每個具體的類都增加一些自己特有的東西。在Java 術語學中,被繼承的類叫超類(superclass ),繼承超類的類叫子類(subclass )。因此,子類是超類的一個專門用途的版本,它繼承了超類定義的所有實例變數和方法,並且為它自己增添了獨特的元素。

繼承一個類,只要用extends 關鍵字把一個類的定義合並到另一個中就可以了。為了理解怎樣繼承,讓我們從簡短的程序開始。下面的例子創建了一個超類A和一個名為B的子類。注意怎樣用關鍵字extends 來創建A的一個子類。

// A simple example of inheritance.
// Create a superclass.
class A {
int i, j;
void showij() {
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A {
int k;
void showk() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}
class SimpleInheritance {
public static void main(String args[]) {
A superOb = new A();
B subOb = new B();
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
}

該程序的輸出如下:

Contents of superOb:
i and j: 10 20

Contents of subOb:
i and j: 7 8
k: 9

Sum of i, j and k in subOb:
i+j+k: 24

像你所看到的,子類B包括它的超類A中的所有成員。這是為什麼subOb 可以獲取i和j 以及調用showij( ) 方法的原因。同樣,sum( ) 內部,i和j可以被直接引用,就像它們是B的一部分。

盡管A是B的超類,它也是一個完全獨立的類。作為一個子類的超類並不意味著超類不能被自己使用。而且,一個子類可以是另一個類的超類。聲明一個繼承超類的類的通常形式如下:

class subclass-name extends superclass-name {
// body of class
}

你只能給你所創建的每個子類定義一個超類。Java 不支持多超類的繼承(這與C++ 不同,在C++中,你可以繼承多個基礎類)。你可以按照規定創建一個繼承的層次。該層次中,一個子類成為另一個子類的超類。然而,沒有類可以成為它自己的超類。

成員的訪問和繼承
盡管子類包括超類的所有成員,它不能訪問超類中被聲明成private 的成員。例如,考慮下面簡單的類層次結構:

/* In a class hierarchy, private members remain private to their class.

This program contains an error and will not compile.
*/

// Create a superclass.

class A {
int i;
private int j; // private to A
void setij(int x, int y) {
i = x; j = y;
}
}
// A"s j is not accessible here.
class B extends A {
int total; void sum() {
total = i + j; // ERROR, j is not accessible here
}
}
class Access {
public static void main(String args[]) {
B subOb = new B();
subOb.setij(10, 12);
subOb.sum();
System.out.println("Total is " + subOb.total);
}
}

該程序不會編譯,因為B中sum( ) 方法內部對j的引用是不合法的。既然j被聲明成private,它只能被它自己類中的其他成員訪問。子類沒權訪問它。

注意:一個被定義成private 的類成員為此類私有,它不能被該類外的所有代碼訪問,包括子類。

更實際的例子
讓我們看一個更實際的例子,該例子有助於闡述繼承的作用。新的類將包含一個盒子的寬度、高度、深度。

// This program uses inheritance to extend Box.

class Box {
double width; double height; double depth;
// construct clone of an object
Box(Box ob) { // pass object to constructor
width = ob.width;
height = ob.height;
depth = ob.depth;
}
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
// compute and return volume double
volume() {
return width * height * depth;
}
}

BoxWeight extends Box {
double weight; // weight of box
// constructor for BoxWeight
BoxWeight(double w, double h, double d, double m) {
width = w;
height = h;
depth = d;
weight = m;
}
}
class DemoBoxWeight {
public static void main(String args[]) {
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
System.out.println("Weight of mybox1 is " + mybox1.weight);
System.out.println();
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
System.out.println("Weight of mybox2 is " + mybox2.weight);
}
}

該程序的輸出顯示如下:

Volume of mybox1 is 3000.0
Weight of mybox1 is 34.3

Volume of mybox2 is 24.0
Weight of mybox2 is 0.076

BoxWeight 繼承了Box 的所有特徵並為自己增添了一個weight 成員。沒有必要讓BoxWeight 重新創建Box 中的所有特徵。為滿足需要我們只要擴展Box就可以了。

繼承的一個主要優勢在於一旦你已經創建了一個超類,而該超類定義了適用於一組對象的屬性,它可用來創建任何數量的說明更多細節的子類。每一個子類能夠正好製作它自己的分類。例如,下面的類繼承了Box並增加了一個顏色屬性:

// Here, Box is extended to include color.
class ColorBox extends Box {
int color; // color of box
ColorBox(double w, double h, double d, int c) {
width = w;
height = h;
depth = d;
color = c;
}
}

記住,一旦你已經創建了一個定義了對象一般屬性的超類,該超類可以被繼承以生成特殊用途的類。每一個子類只增添它自己獨特的屬性。這是繼承的本質。

超類變數可以引用子類對象
超類的一個引用變數可以被任何從該超類派生的子類的引用賦值。你將發現繼承的這個方面在很多條件下是很有用的。例如,考慮下面的程序:

class RefDemo {
public static void main(String args[]) {
BoxWeight weightbox = new BoxWeight(3, 5, 7, 8.37);
Box plainbox = new Box(); double vol;
vol = weightbox.volume();
System.out.println("Volume of weightbox is " + vol);
System.out.println("Weight of weightbox is " + weightbox.weight);
System.out.println();
// assign BoxWeight reference to Box reference
plainbox = weightbox;
vol = plainbox.volume(); // OK, volume() defined in Box
System.out.println("Volume of plainbox is " + vol);
/* The following statement is invalid because plainbox does not define a weight member. */
// System.out.println("Weight of plainbox is " + plainbox.weight);
}
}

這里,weightbox 是BoxWeight 對象的一個引用,plainbox 是Box對象的一個引用。既然BoxWeight 是Box的一個子類,允許用一個weightbox 對象的引用給plainbox 賦值。

當一個子類對象的引用被賦給一個超類引用變數時,你只能訪問超類定義的對象的那一部分。這是為什麼plainbox 不能訪問weight 的原因,甚至是它引用了一個BoxWeight 對象也不行。仔細想一想,這是有道理的,因為超類不知道子類增加的屬性。這就是本程序中的最後一行被注釋掉的原因。Box的引用訪問weight 域是不可能的,因為它沒有定義。
是否可以解決您的問題?

G. java編程 要用到繼承的方法

代碼如下。輸入參數和計算結果都為整數。具體類型請自行修改。

importjava.util.Scanner;
publicclassTest{
publicstaticvoidmain(String[]args){
while(true){
Shapeshape=showMenu();
System.out.println("所選圖形的周長為:"+shape.getRound());
System.out.println("所選圖形的面積為:"+shape.getArea());
shape=null;
}
}
publicstaticShapeshowMenu(){
Shapeshape=null;
System.out.println("請選擇圖形:");
System.out.println("1圓2矩形3三角形9退出");
intoption=Shape.getInput();
switch(option){
case1:
shape=newCircle();
break;
case2:
shape=newRectangle();
break;
case3:
shape=newTriangle();
break;
case9:
System.out.println("系統退出!");
System.exit(0);
break;
default:
System.out.println("選項不存在");
shape=showMenu();
break;
}
returnshape;
}
}
abstractclassShape{
/**
*給圖形的參數賦值。
*@paramsc
*/
abstractvoidgetParam();
/**
*獲取周長
*@return
*/
abstractintgetRound();
/**
*獲取面積
*@return
*/
abstractintgetArea();
/**
*獲取輸入的參數
*@paramsc
*@return
*/
publicstaticintgetInput(){
intx=Integer.MIN_VALUE;
try{
x=newScanner(System.in).nextInt();
if(x<0){
thrownewException();
}
}catch(Exceptione){
System.out.println("輸入錯誤,請重新輸入");
x=getInput();
}
returnx;
}
}
//矩形
classRectangleextendsShape{
privateintside1;
privateintside2;
publicRectangle(){
getParam();
}
voidgetParam(){
System.out.println("第一條邊:");
this.side1=getInput();
System.out.println("第二條邊:");
this.side2=getInput();
};
intgetRound(){
return2*(side1+side2);
}
intgetArea(){
returnside1*side2;
}
}
//圓形
classCircleextendsShape{
privateintr;
publicCircle(){
getParam();
}
voidgetParam(){
System.out.println("請輸入半徑:");
this.r=getInput();
}
intgetRound(){
return(int)(2*Math.PI*r);
}
intgetArea(){
return(int)(Math.PI*r*r);
}
}
//三角形
classTriangleextendsShape{
privateintside1;
privateintside2;
privateintside3;
publicTriangle(){
getParam();
}
voidgetParam(){
System.out.println("第一條邊:");
this.side1=getInput();
System.out.println("第二條邊:");
this.side2=getInput();
System.out.println("第三條邊:");
this.side3=getInput();
if(!isTriangle()){
System.out.println("無法構成三角形,請重新輸入");
getParam();
}
}
intgetRound(){
returnside1+side2+side3;
}
intgetArea(){
System.out.println("三角形面積計算稍顯復雜,請自行寫代碼。");
return0;
}
privatebooleanisTriangle(){ //根據兩邊之和大於第三邊判斷是否能構成三角形
returnside1+side2>side3&&side1+side3>side2&&side2+side3>side1;
}
}

H. 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";
}

}

I. 簡單的java 編程題 關於繼承

package javaapplication4;
public class Rect {
protected int length;/////這個地方不能變成私有屬性,因為後面繼承的類也需要繼承它。
protected int width;
public Rect(int length,int width)
{
this.length=length;
this.width=width;
}
public void setLength(int length)
{this.length=length;<br> }
public void setWidth(int width)
{this.width=width;<br> }
public int getLength()
{return length;<br> }
public int getWidth()
{return width;<br> }
public int getArea()
{return length*width;<br> }
public int getCycle()
{return (length+width)*2;<br> }}
////////////////////////////////////////////////////////////////////////////////////////////////////////
package javaapplication4;
public class PlainRect extends Rect
{///此類並未繼承父類的長寬屬性,所以父類的設計是不合理的。應將其屬性改為protected.
protected int startX,startY;
public PlainRect(int length,int width,int startx,int starty)
{
super(length,width);
startX=startx;
startY=starty;
}
public PlainRect()
{
super(0,0);
startX=0;
startY=0;
}
public boolean isInside(double x,double y)
{
boolean b=false;
if(x>startX&&x<startX+length)
if(y>startY&&y<startY+width)
b=true;
return b; }}
////////////////////////////////////////////////////////////////////////////////////////////////////////
package javaapplication4;
public class Main {
public static void main(String[] args) {
PlainRect Pr1=new PlainRect(20,10,10,10);
System.out.println("面積為:"+Pr1.getArea());
System.out.println("周長為:"+Pr1.getCycle());
System.out.println("點(25.5,13)"+(Pr1.isInside(25.5, 13)?"在":"不在")+"此方形內");
} }

J. 類的繼承的java編程

class user
{
String name,id;
static int count=0;
user()
{
name="zhangsan";
id="123456";
count++;
}
user(String n)
{
name=n;
count++;
}
user(String n,String i)
{
name=n;
id=i;
count++;
}
void setId(String i){
id=i;
}
String getName(){
return name;
}
String getId(){
return id;
}
int getCount(){
return count;
}
void massage(){
System.out.println("用戶名為:"+getName());
System.out.println("用戶口令為:"+getId());
System.out.println("此為第"+getCount()+"個用戶");
}
}
class useryy{
public static void main (String args[]){
user user1=new user();
user1.massage();
user user2=new user("lisi");
user2.setId("456123");
user2.massage();
user user3=new user("xiaozhang","456985");
user3.massage();
}
}

閱讀全文

與java繼承編程相關的資料

熱點內容
愛情動作電影 瀏覽:807
八零電子書txt免費下載網站 瀏覽:508
登陸遼事通顯示伺服器連接錯誤怎麼辦 瀏覽:547
9米高隧道演算法 瀏覽:508
池袋最強作品集txt 瀏覽:782
app專題推薦在哪裡 瀏覽:277
神雲伺服器顯示燈 瀏覽:134
程序員磨合期技巧 瀏覽:847
鬼團六全部電影名稱 瀏覽:864
穿越唯一一個女人世界 瀏覽:645
飛言情小說官網入口 瀏覽:581
pdf壓縮後還清晰嗎 瀏覽:654
得到app的電子書書架在哪裡 瀏覽:151
管道彎頭製作演算法 瀏覽:37
phpmvcsmarty實例 瀏覽:925
spring搭建http伺服器地址 瀏覽:713
servlet教程pdf 瀏覽:970
蜂鳥眾包app如何聯系客服 瀏覽:188
程序員t恤淘寶 瀏覽:94
自助研發app如何推廣 瀏覽:727