Skip to content

Instantly share code, notes, and snippets.

@speters33w
Last active April 26, 2022 20:24
Show Gist options
  • Save speters33w/2ed21dc4554db6b82a4c9c4a1d7b2e2c to your computer and use it in GitHub Desktop.
Save speters33w/2ed21dc4554db6b82a4c9c4a1d7b2e2c to your computer and use it in GitHub Desktop.
this.keyword = keyword;
public class MyThisTest {
private int a;
public MyThisTest() {
this(42); // calls the other constructor
}
public MyThisTest(int a) {
this.a = a; // assigns the value of the parameter a to the field of the same name
}
public void frobnicate() {
int a = 1; // refers to the local variabla a
System.out.println("Local variable a = " + a); // refers to the local variable a
System.out.println("This field a = " + this.a); // refers to the field a
System.out.println(this + "\n"); // refers to this entire object
}
@Override
public String toString() {
return "This entire object a = " + a; // refers to the field a
}
}
import java.util.Random;
import java.util.Scanner;
public class MyThisTestTest{
public static void main(String[] args){
MyThisTest test1 = new MyThisTest();
test1.frobnicate();
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
String userInput = scanner.nextLine();
int a = 27;
if (!userInput.equals("")){
a = Integer.parseInt(userInput);
} else {
System.out.println("OK, random it is.");
Random random = new Random();
a = random.nextInt(99);
}
MyThisTest test2 = new MyThisTest(a);
test2.frobnicate();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment