b); } public static void main(String[] args) { ThisExample obj = new ThisExample(10, 20); obj.display(); } } Powered By In this example, the this keyword is used to differentiate between instance variables a and b and the constructor parameters a and b. Example 2: Invoking a ...
System.out.println("number="+number+";number="+number2);}public static voidmain(String[] args) { ThisDemo tt=newThisDemo();tt.increment().increment().increment().print();} }
java语言给了keywordthis这个功能,那就是用this调用构造函数,并且也是通过參数不同选择调用不同的构造函数. 我们来看一个样例: classPerson{privateStringname;privateintage;Person()//构造方法1{System.out.println("person run");}Person(Stringname)//构造方法2{=name;}Person(Stringname,intage)//构造方法3{=...
就用thiskeyword。 为了更好的理解这个结论,我们把上面的样例能够标准的写成以下这样: classPerson{privateStringname;privateintage;Person(Stringname,intage){=name;this.age=age;}publicvoidspeak(){System.out.println(+":"+this.age);}} 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. ...
recordPerson(Longid,Stringname,intage){}publicclassAssertExample{publicstaticvoidmain(String[]args){Personperson=newPerson(1L,"Lokesh",40);//Passes successfullyassertperson.age()>=18:"Age is less than 18";}} This helps in conditions when the person’s age falls below the expectation. ...
1)通过thiskeyword能够明白的訪问成员变量。解决与局部变量重名的矛盾! (成员变量与局部变量冲突的时候) class Student{ int id; public Student(int id){ this.id=id; } public int getId(){ return this.id; } } 构造方法中的參数是id,它是一个局部变量与成员变量id重名。
Example 1: Basic For Loop publicclassBasicForLoop{publicstaticvoidmain(String[]args){for(int i=0;i<5;i++){System.out.println("Iteration: "+i);}}} In this example, the loop initializesito 0, checks ifiis less than 5, and incrementsiby 1 after each iteration. The loop prints the va...
Reason is that whenever any final field/reference is evaluated as “constant expression“, it is serialized by JVM ignoring the presence of transient keyword. In above example, value “password” is a constant expression and instance of logger “demo” is reference. So by rule,confidentialInfowas...
In Java, the final class cannot be inherited by another class. For example, // create a final classfinalclassFinalClass{publicvoiddisplay(){ System.out.println("This is a final method."); } }// try to extend the final classclassMainextendsFinalClass{publicvoiddisplay(){ ...
, we pass a reference to the current instance. 5. returning this we can also use this keyword to return the current class instance from the method. to not duplicate the code, here’s a full practical example of how it’s implemented in the builder design pattern . 6. the this...