本文目錄一覽:
Java裡面的this關鍵字是什麼意思
this關鍵字可以簡單的理解為,誰調用this所在的方法,this就是誰。
類的構造函數與getter、setter方法常用到this關鍵字(JavaBean)
JavaBean是一種可重用的Java組件,它可以被Applet、Servlet、SP等Java應用程序調用.也可以可視化地被Java開發工具使用。它包含屬性(Properties)、方法(Methods)、事件(Events)等特性。
public class Person {
//==========靜態屬性===========
//–想學編程的可以來我這看看—-
private String name; //姓名
private int age; //年齡
private String gender; //性別
//==========動態行為===========
public void readBook(String book) {
System.out.println(“reading ” + book);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;//this.name就是上面的private String name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
官方定義
this 是自身的一個對象,代表對象本身,可以理解為:指向對象本身的一個指針。
this 的用法在 Java 中大體可以分為3種:
1.普通的直接引用
這種就不用講了,this 相當於是指向當前對象本身。
2.形參與成員名字重名,用 this 來區分:
class Person {
private int age = 10;
public Person(){
System.out.println(“初始化年齡:”+age);}
public int GetAge(int age){
this.age = age;
return this.age;
}
}
public class test1 {
public static void main(String[] args) {
Person Harry = new Person();
System.out.println(“Harry’s age is “+Harry.GetAge(12));
}
}
希望對您有所幫助!~
java中this的用法
java中this有兩種用法:
1、代表當前類
public class Dog{
private String name;
private float age;
public setName(String name){
this.name = name;
}
…….
}
這裡的this就代表的當前的這個Dog類。this.name可以理解為dog.name,只是理解,不是等於。
2、在構造函數中的使用
public class Dog{
private String name;
private int age;
//有一個參數的構造函數
public Dog(String name){
this.name = name;
}
public Dog(String name,int age){
this.name = name;
this.age = age;
}
//這個無參構造方法里調用的有兩個參數的構造方法,這個也就是this的第二種用法了!
public Dog(){
this(“nihao”,20);
}
}
java中this的關鍵字用法是什麼?
Java關鍵字this只能用於方法方法體內。當一個對象創建後,Java虛擬機(JVM)就會給這個對象分配一個引用自身的指針,這個指針的名字就是 this。
this主要要三種用法:
表示對當前對象的引用。
表示用類的成員變數,而非函數參數,注意在函數參數和成員變數同名是進行區分。這是第一種用法的特例,比較常用。
用於在構造方法中引用滿足指定參數類型的構造器(其實也就是構造方法)。注意:只能引用一個構造方法且必須位於開始。
this不能用在static方法中!有人給static方法的定義:沒有this的方法。
原創文章,作者:HXIQ,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/143355.html