1. 程式人生 > >2018.12.28this關鍵字呼叫書名屬性的三個型別題

2018.12.28this關鍵字呼叫書名屬性的三個型別題

一.this關鍵字呼叫書名屬性的三個型別題

1.建立一個借書類BorrowABook,借書類中有書名屬性name,引數為name的構造方法和借書方法borrow()。編寫一個程式,使用this關鍵字呼叫書名屬性後,借閱《戰爭與和平這本書》

package myObject;

public class BorrowABook {
	//成員變數name
	String name;
	//有參構造方法
	public BorrowABook(String name) {
		this.name = name;//將有參構造方法中的引數name的值賦給屬性name
	}
	//成員方法borrow
	public void borrow() {
		//在此輸出屬性的值
		System.out.println("請前往借閱處領取"+name);
	}
	//主方法
	public static void main(String[] args) {
		//建立新物件
		BorrowABook a = new BorrowABook("《戰爭與和平》");
		//呼叫方法
		a.borrow();
	}
}

2.建立教師類,類中有姓名、性別、和年齡三個屬性,在構造方法中使用this關鍵字分別為這三個成員屬性賦值
我的程式碼:

package myObject;

public class TeachMan {
	String name;
	String sex;
	int age;
	public TeachMan(String name,String sex,int age) {
		this.name = name;
		this.sex = sex;
		this.age = age;
	}
	public void Teach() {
		System.out.println("姓名為:"+name);
		System.out.println("性別為:"+sex);
		System.out.println("年齡為:"+age);
	}
	public static void main(String[] args) {
		TeachMan a = new TeachMan("張三","男",18);//要和上面有參構造格式一樣
		a.Teach();
		TeachMan b = new TeachMan("李四","男",19);
		b.Teach();
		TeachMan c = new TeachMan("王五","男",20);
	}

}

答案程式碼:

package myObject;

public class Teacher {
	String name;
	char sex;
	int age;
	
	public Teacher(String name, char sex, int age) {
		this.name = name;
		this.sex = sex;
		this.age = age;
		System.out.println("教師姓名:" + name + "\n教師性別:" + sex + "\n教師年齡:" + age);
	}
	public static void main(String[] args) {
		Teacher chinese = new Teacher("張三", '男', 38);
		Teacher math = new Teacher("李四", '男', 45);
		Teacher english = new Teacher("王莉", '女', 32);
	}
}

①.有無參構造方法,建立物件下面寫呼叫方法;沒有無參方法,直接在有參方法內輸出,不寫呼叫方法
②.如果有參方法中為多個引數,給物件賦值時要與引數格式一致,一對一,多對多
3.一隻大熊貓,長1.3米,重90千克。在自定義方法中使用this關鍵字呼叫類的成員變數並在控制檯輸出大熊貓資訊

package myObject;

public class Panda {
	private double length = 1.3;
	private double weight = 90.0;

	public String getMessages() {
		return "熊貓體長" + this.length + "米,體重" + this.weight + "KG。";
	}

	public static void main(String[] args) {
		Panda panda = new Panda();
		System.out.println(panda.getMessages());
	}
}

①.寫無參方法,直接在主方法中輸出"物件.無參方法"