Dog類無參及有參構造方法
阿新 • • 發佈:2019-01-03
import java.util.Scanner;
class Dog{
String name="多多";
String color="黑白";
String hair="長毛";
String body="小狗";
int age=2;
Dog(){
System.out.println("Dog的無參構造方法。");
}
Dog(String n,String c,String h,String b,int a){
name=n;
color=c;
hair=h;
body=b;
age=a;
}
void printInfo(){
System.out.println("狗的名字是:"+name);
System.out.println("狗的顏色是:"+color);
System.out.println("狗的毛長是:"+hair);
System.out.println("狗的體型是:"+body);
System.out.println("狗的年齡是:"+age);
}
}
public class DogTest{
public static void main(String[] args){
Scanner reader=new Scanner(System.in);
Dog dog1=new Dog();
System.out.println("請輸出狗1的資訊:");
dog1.printInfo();
System.out.println("請輸入狗2的資訊:");
System.out.println("狗的名字為:");
String n=reader.next();
System.out.println("狗的顏色為:");
String c=reader.next();
System.out.println("狗的毛長為:");
String h=reader.next();
System.out.println("狗的體型為:");
String b=reader.next();
System.out.println("狗的年齡為:");
int a=reader.nextInt();
Dog dog2=new Dog(n,c,h,b,a);
System.out.println("請輸出狗2的資訊:");
dog2.printInfo();
}
}
class Dog{
String name="多多";
String color="黑白";
String hair="長毛";
String body="小狗";
int age=2;
Dog(){
System.out.println("Dog的無參構造方法。");
}
Dog(String n,String c,String h,String b,int a){
name=n;
color=c;
hair=h;
body=b;
age=a;
}
void printInfo(){
System.out.println("狗的名字是:"+name);
System.out.println("狗的顏色是:"+color);
System.out.println("狗的毛長是:"+hair);
System.out.println("狗的體型是:"+body);
System.out.println("狗的年齡是:"+age);
}
}
public class DogTest{
public static void main(String[] args){
Scanner reader=new Scanner(System.in);
Dog dog1=new Dog();
System.out.println("請輸出狗1的資訊:");
dog1.printInfo();
System.out.println("請輸入狗2的資訊:");
System.out.println("狗的名字為:");
String n=reader.next();
System.out.println("狗的顏色為:");
String c=reader.next();
System.out.println("狗的毛長為:");
String h=reader.next();
System.out.println("狗的體型為:");
String b=reader.next();
System.out.println("狗的年齡為:");
int a=reader.nextInt();
Dog dog2=new Dog(n,c,h,b,a);
System.out.println("請輸出狗2的資訊:");
dog2.printInfo();
}
}