Sitemap
Karnan Sooriyakumar

Karnan Sooriyakumar

How Objects Behave

2 min readMar 20, 2022

--

Instance Variable and Methods

State affects behavior, behavior affects state. We know that objects have state and behavior, represented by Instance variables and methods.

A class describes what an object knows and what an object does.

Methods can return values. Every method is declared with a return type. If we declare a method with void type, that don not give anything back.

Void go(){}

If you declare a method to return a value, you must return a value of the declared type or return value is compatible with declared type.

int gveSecret(){  return 42;}

A method can have parameters, which means you can pass one or more values into the method. If a method has parameters, you must pass arguments of the right type and order.

Press enter or click to view image in full size

Encapsulation

A java class says, I always keep my variables private. If you want to see them, you have to talk to my methods this approach is called as encapsulation.

Encapsulation in Java is a process of wrapping code and data together into a single unit. The Java Bean class is the example of a fully encapsulated class.

Example

Get Karnan Sooriyakumar’s stories in your inbox

Join Medium for free to get updates from this writer.

create a class with private variables and public setters and getters methods.

public class Student{  //private data member  private String name;  //getter method for name  public String getName(){  return name;  }  //setter method for name  public void setName(String name){  this.name=name  }}

Instance variables always get a default value. If you don’t explicitly assign a value to an instance variable, or you don’t call a setter method, the instance variable still has a value.

integers 0floating points 0.0boolean falsereferences null

Local variables do not get a default value! The compiler complains if you try to use a local variable before the variable is initialized.

Comparing variables (Primitives or References)

Use == to compare two primitives, or to see if two references refer to the same object.

Use the equals() method to see if two different objects are equal. (Such as two different String objects that both represent the characters In “Freel”).

References

[1] Sierra, K., & Bates, B. (2005). Head First Java, 2nd Edition (2nd ed.). O’Reilly Media.

--

--