Object Oriented

Property

Java

 

Defining Property

Java 8
class Person {
  
  public String name;
  public int age;
  
}

Properties are like variables.

Properties keep the state of the current object.

public keyword defines the visibility of the property here. Check Visibility Topic for more on this.

 

Property initial value

Java 8
class Person {
  
  public String name = "Sam";
  public int age = 25;
  
}

Properties in Java can be initialized with values on declaration.

 

Accessing Properties

Java 8
Person person1 = new Person();

person1.name = "Sarah";
String theName = person1.name;   // "Sarah"

You can access properties (and methods) of an object using the . operator (if that property is visible in that context. Check Visibility Topic for more on this).

Here, since name is a public property (defined on previous cards) you can access it.

 

this

Java 8
class Person {
  
  public String name;
  public int age;
  
  public void greet() {
    System.out.println("Hi! I'm " + name);
  }
  
  public void birthday() {
    this.age = this.age + 1;
  }
  
}

this is a property in all classes pointing to the current object created from that class.

In order to access the properties and methods from within the class, you can simply use the property or method name.

In cases that it is ambiguous, you can use this keyword followed by . operator to access properties and methods.