Programming‎ > ‎Java‎ > ‎

2.Objects and Classes

Introduction to OOP


  • Encapsulation (sometimes called data hiding) is a key concept in working with object.
  • Formally, encapsulation is nothing more than combining data  and behavior in one package and hiding the implementation of the data from the user of the object.
  • The data is an object are called its instance fields (state of object), and the functions and procedures that operate on the data are called its methods.
  • We say that a class that builds on another class extends it.
  • Java, in fact, comes with a "cosmic superclass" called naturally enough, Object, because it is the factory for all objects. All other classes extend this class.
  • The concept of extending a class to obtain another class is called inheritance.


  • Three key characteristics of objects
  • The object's behavior - what can you do with this object, or what methods can you apply to it?
  • The object's state - how does the object react when you apply those methods?
  • The object's identity - how is the object distinguished from others that may have the same behavior and state?
  • A change in the state of an object must be a consequence of methods calls. (If the object state changed without a method call on that object, someone broke encapsulation.)
  • Individual objects that are instances of a class always differ in this identity and usually diff in their state.
  • Minimize the coupling between classes

Create a Class

  • Difference between objects and object variables
  • Date date;  //defined object variable, doesn't refer to any object
  • Date date = new Date(); //initialize the date object variable with object
  • It is important to realize that an object variable doesn't actually contain an object. It only refers to an object, value is a reference to object
  • Local object variables are not automatically initialized to null. Either initialize by calling new or set them to null
  • Methods that change instance fields are called mutator methods and those that only access instance fields without modifying them are called accessor methods.
  • public keyword could be used with instance fields, however it breaks incapsulation

  • Note instance fields for String and Date are objects themselves
  • The name of the source file is since the name of the file must match the name of the public class.
  • You can only have one public class in a source file, but you can have any number of non-public classes
  • When you compile this source code, the compiler creates two class files in the directory EmployeeTest.class and Employee.class

  • You can place the class Employee into a file and EmployeeTest into
  • You have two choices for compiling the program
  • javac Employee*.java
  • javac    // is implicitly compiles as referenced in EmployeeTest
  • Timestamp of existing Employee.class determines if it gets recompiled

  • Be careful not to introduce local variables with the same names as the instance  fields. They shadow the instance fields with the same name
  • In every methods, the keyword this refers to the implicit parameter

  • Be careful not to write accessor methods that return references to mutable objects
  • You should clone it first, before returning reference to mutable object
  • A clone is exact copy of an object that is stored in a new location
  • Method can access the private data of all objects of its class

  • Every class can have main methods. That is a handy trick for unit testing  of classes
  • To test Employee - java Employee
  • To test EmployeeTest - java EmployeeTest


import java.util.*

public class EmployeeTest
  public static void main(String[] args)

    Employee[] staff = new Employee[3];
    staff[0] = new Employee("Carl", 75000, 1987, 12, 15);

class Employee
  public Employee(String name, double s, int y, int m , int d) { = n; ... }
  public String getName() { return name; }
  public double getSalary() { return s; }
  public Date getDate() {return (Date)date.clone(); }

  public equals(Employee other) { return; }

  private String name;
  private double salary;
  private Date date;

Final Instance Fields

  • Define an instance field as final, the final field must be initialized when the object is constructed
  • It must be guaranteed that the field value is set after the end of every constructor
  • Afterwards, the field may not be modified again
  • private final String name;
  • It is good idea to tag fields that don't change during object lifetime to final
  • If all the fields of a class are final, class is immutable - its objects never change after they are constructed, e.g. String and Date
  • Immutable classes, you don't have to worry about sharing references
  • public final fields are ok, don't break encapsulation

Static Fields and Methods

Static Fields

  • If you define a field as static, then there is only one such field per class. In contrast, each object has its own copy of all instance fields
  • Even if there are no class objects, the static field is present. It belongs to the class, not to any individual object

Static Methods

  • Static methods are methods that do not operate on objects and don't have this parameter
  • You can not access instance fields from a static method
  • Static method can access the static fields in their class
  • Static Methods are access by class instead of object

Method Parameters

  • The Java programming language always uses call by value
  • Two kinds of methods parameters - Primitive types (numbers) and Object references
  • It is impossible for a method to change a primitive type parameter (Refer call by value)
  • Objects references are passed by value
  • Employee a, b; // 
  • swap (a, b); // Does not swap reference for a,b
  • A method can change the state of an object parameter
  • A method cannot make an object parameter refer to a new object

Object Construction

  • A constructor has the same name as the class
  • A class can have more than one constructor
  • A constructor may take zero, one, or more parameters
  • A constructor has no return value
  • A constructor is always called with the new operator


  • Java allows you to overload any method - including constructor methods with different parameters
  • Signature of method is name and parameter types
  • indexOf(int)
  • indexOf(int, int)
  • The return type is not part of the method signature. 

Default Field Initialization

  • If you don't set a field explicitly in a constructor, it is automatically set to a default value; numbers to zero, Boolean to false, object references to null

Default Constructor

  • A default constructor is a constructor with no parameters
  • If you write class with no constructors, then a default constructor is provided for you
  • If you write class with atleast one constructor, then a implicit default constructor is not provided for you. In such case user has to write own default constructor with no parameters. It is illegal and error to constructor objects with default constructor without defining it explicitly

Explicit Field Initialization

  • You can simply assign a value to any field in the class definition
  • This assignment is carried out before the constructor executes
  • private String name = "";

Calling Another Constructor

  • The keyword this refers to the implicit parameter of a method. However, there is a second meaning for the keyword
  • If the first statement of a constructor has the form this(...), the the constructor calls another constructor of the same class
public class Employee {

  public Employee (double s) {
    // calls Employee(String, double)
    this("Employee #" + nextId, s)

Initialization Blocks

  • Ways to initialize a data field - executes in order
  • - By setting value in the declaration
  • - By setting value in the initialization block
  • - By setting value is a constructor
  • Class declaration can contain arbitrary blocks of code. These blocks are executed whenever an object  of that class is constructed
  • The initialization block runs first, and then the body of the constructor is executed
  • If the static fields of your class require complex initialization code, use a static initialization block
  • Static initialization occurs when the class is first loaded
class Employee {

 // static initialization block
    nextId = 0;
  // object initialization block
     id = nextId;

  private int id;
  private static int nextId;

  • You can write a "Hello World" program in Java without ever writing a main method
public class Hello {
  static {
    System.out.println("Hello, World");

Object Construction Steps

  • Here is what happens in detail when a constructor is called
  • a. All the data fields are initialized to their default value (o, false or null)
  • b. If the first line of constructor  calls another constructor, then that constructor is executed. Otherwise, all field initializers and initialization blocks are executed, in the order  in which they occur in the class declaration
  • The body of the constructor is executed

Object Destruction and the finalize Method

  • The most common activity in a destructor is reclaiming the memory set aside for objects
  • Since Java does automatic garbage collection, manual memory reclamation is not needed, and Java does not support destructors
  • The finalize method will be called before the garbage collector sweeps away the object. Do not reply on finalize method.


  • Java allows you to group classes in a collection called a package
  • All standard packages are under java and javax
  • A class can use all classes from its own package and all public classes from other packages
  • java.util.Date today = new java.util.Date();
  • import java.util.*
  • import java.util.Date;
  • Add a class into a package
  • package com.deepak.sample;
  • If you don't put a package statement in the source file, then the classes in that source file belong to the default package. The default package has no package name

Access Modifiers

  • class - public or default
  • method\data - private, default, protected, public
  • Private - Like you'd think, only the class in which it is declared can see it
  • Package Private - Can only be seen and used by the package in which it was declared. This is the default in Java (which some see as a mistake)
  • Protected - Package Private + can be seen by subclasses in other package
  • Public - Everyone can see it

Class Design Hints

  • Always keep data private
  • Always initialize data
  • Don't use too many basic types in a class
  • - Use multiple basic types with other class
  • Not all fields need individual field accessors and mutators
  • Use a standard form for class definitions
List the contents of classes in the following order
public features
package scope features
private features

List within each section
instance methods
static methods
instance fields
static fields
  • Break up classes with too many responsibilities
  • Make the names of classes and methods reflect their responsibilities