Skip to content
Tutorials Center
My learning

Topics

Lesson 198 of 201 ยท Practice and Review

Class and Object Programs in Java

Practice object-oriented Java with runnable programs - singleton, static members and init order, overriding vs overloading, data hiding, abstract classes and access modifiers.

Object-oriented programming is easy to nod along to and hard to get right under pressure. Interviewers and exams love the same handful of small programs: "write a singleton", "what does this static block print", "which overload gets called", "show encapsulation", "why can't I create an object of this abstract class", "what can a subclass see?". Each one is short, and each hides one precise rule of the language.

This page walks through those programs one at a time. Every example is complete and runnable, and every one ends with the output you should expect. Read the code, predict the output, then run it. If your prediction was wrong, that is exactly the rule worth remembering. The classes here use the classic public class Main layout because several of the rules (package-private access, top-level classes) are easier to see that way. If you need the theory first, start with Static Members, Polymorphism and Access Modifiers.

Singleton: exactly one instance

A singleton is a class that allows only one object. The recipe has three parts: a private constructor so nobody else can call new, a static field that holds the single instance, and a static method that hands it out. Java gives you three practical ways to write it:

  • Eager instance in a static final field. The object is created when the class loads. Simple and thread-safe.
  • Enum with one constant. The shortest form, and the only one that is also safe against reflection and serialization tricks.
  • Holder class. A private nested class that owns the instance. The object is created the first time get() is called, and the JVM's class-loading rules make that thread-safe without any synchronized.
Java Three ways to write a singleton

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Look at the order of the two static fields in Settings. Static fields are initialized top to bottom. If you move created = 0 below the INSTANCE line, the constructor runs first and sets created to 1, and then the initializer = 0 runs and resets it, so timesCreated() prints 0. It is a famous trap, and it is the reason to keep static fields that a constructor touches above the instance.

If you use a dependency injection framework, you rarely write a singleton by hand. The framework creates one object per application and passes it in, which is much easier to test than a global getInstance().

Static members and initialization order

A static member belongs to the class, not to any object. Fields are shared by every instance, methods can be called without an object, and a static { } block runs once, when the class is first used. An instance initializer block ({ }) runs before the constructor body, every time an object is created. The program below prints a trace so you can watch the order. Notice that the static block runs after main starts: classes are initialized lazily.

Java Static block, instance block and shared counter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The rules in one place: a static method cannot touch instance fields (it has no this); an instance method can use both; and static final constants are the right home for values that never change.

Overriding versus overloading

These two words sound alike and mean different things.

  • Overriding replaces an inherited method in a subclass with the same signature. It is resolved at run time from the object's real class, so it is the engine behind polymorphism. Always add @Override: the compiler then rejects typos.
  • Overloading means several methods with the same name but different parameter lists in one class. It is resolved at compile time from the declared types of the arguments.
  • Static methods are not overridden. A subclass static method with the same signature hides the parent's, and the call is decided by the variable's declared type.

For overloads, the compiler tries, in order: an exact match, a widening primitive conversion (byte to int), boxing, then varargs. The second program shows each case.

Java Overriding, hiding and overload resolution

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Check each line against the rules. print(small) and print(letter) choose int because byte and char widen to int before anything else. print(2.5f) widens float to double. print(text) picks the Object version even though the object is a string, because overloads look at the declared type, not the run-time type. And Integer.valueOf(7) has no Integer overload, so it goes to Object rather than unboxing to int: for an object argument, a subtype match beats unboxing. More in Method Overloading and Polymorphism.

Data hiding (encapsulation)

Data hiding means keeping fields private and letting other code change them only through methods that enforce your rules. The bank account below can never have a negative deposit or go overdrawn, no matter who calls it, because the only way to change balance is through deposit and withdraw. The rule lives in one place, which is what makes the class safe to reuse. This is the idea behind Encapsulation.

Abstract classes

An abstract class is a partly finished class. It can have fields, constructors and ordinary methods, plus abstract methods with no body that every concrete subclass must implement. You cannot create an object of an abstract class directly, but you can use it as a type. A method like describe() in the parent can call area() and trust that the right child version runs. This is the template-method idea from Abstraction and Abstract Classes.

Java Abstract class and encapsulated account

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The access-modifier matrix

Java has four access levels. The table shows who can use a member that is declared with each one.

Modifier Same class Same package Subclass in another package Anywhere else
private yes no no no
(none), package-private yes yes no no
protected yes yes yes, through inheritance no
public yes yes yes yes

The sample program has one class with a field at each level, a second class in the same package that uses it, and some reflection that lists the modifiers. A single file cannot span two packages, so the "subclass in another package" column stays as theory here. Everything outside the class, except private, compiles because Main and Sample share a package.

Java What each access level allows

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Two practical rules follow. Make everything as private as you can and widen access only when something needs it, and remember that leaving the modifier off is not "public" or "private": it means "my package only". See Access Modifiers for the full story, including protected across packages.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In the singleton example, why is the constructor private?

    A private constructor stops other code from calling new, so the class alone controls how many objects exist. Thread safety comes from how the instance is created, not from the constructor's access level.
  2. 2. Animal pet = new Dog(); and both classes define a static method kind(). Which version does pet.kind() call?

    Static methods are hidden, not overridden. The compiler picks the method from the declared type of the variable, which is Animal.
  3. 3. Given overloads print(int), print(Object) and print(String), which one does Object o = "x"; print(o); call?

    Overloads are resolved at compile time from the declared type of the argument. The variable o is declared as Object, so print(Object) is chosen.
  4. 4. What can you do with an abstract class?

    An abstract class cannot be instantiated, but it can have constructors that subclasses call, concrete methods, and it can be used as a type for polymorphism.
  5. 5. A field is declared without any access modifier. Who can access it?

    No modifier means package-private. Classes in the same package can use the member, but classes in other packages cannot, not even subclasses.

Summary

  • A singleton needs a private constructor, a static instance and a static accessor; an enum with one constant is the safest and shortest form.
  • Static fields initialize top to bottom, static blocks run once when the class is first used, instance blocks run before each constructor body.
  • Overriding is chosen at run time by the object's class; overloading is chosen at compile time by the arguments' declared types; static methods are hidden, never overridden.
  • Data hiding means private fields plus methods that enforce the rules, so invalid states cannot happen.
  • Abstract classes cannot be instantiated; they hold shared code and force subclasses to supply the abstract methods.
  • Access levels run from private (class only) through package-private and protected to public; no modifier means package-private.

Next: Exception and Thread Programs, the same kind of rule-hunting practice for errors and concurrency, and then the exercises.