DEV Community

Janardhan Pulivarthi
Janardhan Pulivarthi

Posted on • Updated on

Day 6 of 100 - Java: Classes and Fields

fields of an object are data variables. Also, referred to as attributes or
member variables.

usually made up of primitive types like integers or characters, but can also
be objects themselves.

  1. Access fields

    String title;
    String author;
    int numberOfPages;
    String myBookTitle = book.title;
  2. Setting fields

    book.numberOfPages = 234;
  3. Methods

Run actions in objects looks like calling a function.

Calling a method

void setBookmark(int pageNumber);
Enter fullscreen mode Exit fullscreen mode

Points on Classes

  1. Classes is a blueprint of what the object should look like
  2. Object is the actual entity created from that Class
  3. Classes have all the fields and implements all the methods
  4. Classes and Objects are two different words

Table - Class vs Object

Class Object
What: A Data Type A Variable
Where: Has its own file Scattered around the project
Why: Defines the structure Used to implement to logic
Naming convention: CamelCase (starts with an upper case) camelCase (starts with a lower case)
Examples: Country australia

Table - Java classes around primitive types

Class Primitive type
Integer int
Long long
Double double
Character char
String char[]

code example - Pokemon Class

class Pokemon {
    String name;
    String type;
    int health;

    boolean dodge() {
        return Math.random() > 0.5;

    void attack(Pokemon enemy) {
        if(! {
Enter fullscreen mode Exit fullscreen mode

What each term in main() method definition means?

public static void main(String[] args) {

Enter fullscreen mode Exit fullscreen mode
  • public - Run this method from anywhere in Java program
  • static - Does not need an object to run
  • void - Main method doesn't return any output. It invokes the logic inside the main method
  • main - name of the method
  • String [] args - Input parameter (array of strings)

Java program won't run if the main method is not available or if defined more than once.

Self reference:

  1. To refer an object within one of its methods or constructors, use keyword this.
  2. this is a reference to the current object - the object whose method or constructor is being called.

    class Size {
    int rows = 0;
    int columns = 0;
    // constructor
    Size(int rows, int columns) {
      this.rows = rows;
      this.columns = columns;
  3. With this.rows we are referring to field rows not the input parameter.


An example implemented here:

Private vs public access

  1. Use getters and setters if the public access required for a field
  2. Declare all fields as private where possible
  3. package public is the default. It will label public only in the same package/folder.
  4. Set helper methods to private
  5. Set action methods to public

Top comments (0)