Understanding Java Object Members, Methods, and Initialization
This tutorial explains how Java methods access object data members, the role of the implicit this reference, parameter passing, calling other methods within the same object, and both default and explicit initialization of class fields, using clear code examples throughout.
In this tutorial we explore Java object members, methods, and initialization, building on the earlier introduction to objects and classes.
We demonstrate how a method can access an object's data member by adding a getHeight() method to a Human class, and explain the role of the return statement and the implicit this reference.
public class Test {
public static void main(String[] args) {
Human aPerson = new Human();
System.out.println(aPerson.getHeight());
}
}
class Human {
/** accessor */
int getHeight() {
return this.height;
}
int height;
}We show that this is optional and can be omitted, and we present an alternative version of getHeight() without the explicit this .
int getHeight() {
return height;
}Next we introduce method parameter lists by defining a growHeight(int h) method that increases the object's height field, and we illustrate how arguments are passed and scoped.
public void growHeight(int h) {
this.height = this.height + h;
}We also cover calling other methods of the same object using this.method() , exemplified by a repeatBreath(int rep) method that loops and invokes breath() repeatedly.
public void repeatBreath(int rep) {
for (int i = 0; i < rep; i++) {
this.breath();
}
}Finally we discuss data member initialization, describing default values for primitive types and explicit initialization, and we provide an example where height is set to 175.
int height = 175;The article concludes with a summary of the key points: return , this , default values, and explicit initialization.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.