簡單的Java程式碼實現二
阿新 • • 發佈:2021-01-31
技術標籤:java
理解類的繼承性
1.學生資訊
class Student {
String Name;
int Age;
String Degree;
Student(String n,int a,String d) {
Name=n;
Age=a;
Degree=d;
}
}
class Undergraduate extends Student {
String Professional;
Undergraduate(String n,int a,String d,String p) {
super(n,a,d);
Professional=p;
}
void show() {
System.out.println("本科生:\t姓名:"+Name+"\t年齡:"+Age+"\t學位:"+Degree+"\t專業:"+Professional);
}
}
class Master extends Student {
String Direction;
Master(String n,int a,String d,String dir) {
super(n,a,d);
Direction=dir;
}
void show() {
System. out.println("研究生:\t姓名:"+Name+"\t年齡:"+Age+"\t學位:"+Degree+"\t研究方向:"+Direction);
}
}
public class MyStudent {
public static void main(String args[]) {
Undergraduate undergraduate=new Undergraduate("張三",20,"學士","軟體工程");
Master master= new Master("李四",25,"碩士","網路工程");
undergraduate.show();
master.show();
}
}
2.車輪數量
class Car {
int Number;
int Weight;
Car(int n,int w){
Number=n;
Weight=w;
}
}
class Truck extends Car {
int Load;
Truck(int n, int w,int l) {
super(n, w);
Load=l;
}
void show() {
System.out.println("卡車:\t車輪個數:"+Number+"\t車重:"+Weight+"\t載重量:"+Load);
}
}
class Van extends Car{
int Busload;
Van(int n, int w,int b) {
super(n, w);
Busload=b;
}
void show() {
System.out.println("麵包車:\t車輪個數:"+Number+"\t車重:"+Weight+"\t載客量:"+Busload);
}
}
public class MyCar {
public static void main(String args[]) {
Truck truck=new Truck(16,2000,5000);
Van van=new Van(8,1000,12);
truck.show();
van.show();
}
}
3.圓柱體
class Circle {
public static final double PI=3.14;
int X;
int Y;
double R;
Circle(int x,int y,double r) {
X=x;
Y=y;
R=r;
}
int getX() {
return X;
}
int getY() {
return Y;
}
double getR() {
return R;
}
void perimeter() {
double l;
l=2*PI*R;
System.out.println("周長:"+l);
}
void area() {
double a;
a=PI*R*R;
System.out.println("面積:"+a);
}
}
class Cylinder extends Circle {
Cylinder(int x, int y, double r) {
super(x, y, r);
}
double High;
void sethigh(double h) {
High=h;
}
double getHigh() {
return High;
}
void area(){
double a;
a=2*PI*R*R+2*PI*R*High;
System.out.println("表面積:"+a);
}
void volume(){
double v;
v=PI*R*R*High;
System.out.print("體積:"+v);
}
}
public class MyCircle {
public static void main(String args[]) {
Cylinder cylinder=new Cylinder(0,0,2);
cylinder.sethigh(2);
System.out.println("圓柱體資訊:\n座標:("+cylinder.X+","+cylinder.Y+")\t底面半徑:"+cylinder.R+"\t高度:"+cylinder.High);
cylinder.area();
cylinder.volume();
}
}