AAmit’s LibraryLEARN · PRACTISE · REFLECT

BCA

Java objects, encapsulation, interfaces, and polymorphism

Study map: BCA Semester 2 Java; editorial topic breakdown

An object combines state with behaviour. A class defines the kind of object and its members; an instance is a particular object created from that definition. Modelling begins with responsibilities, not with turning every noun into a class. Ask what information a component owns and which operations it should provide.

1. Model state and behaviour

An object combines state with behaviour. A class defines the kind of object and its members; an instance is a particular object created from that definition. Modelling begins with responsibilities, not with turning every noun into a class. Ask what information a component owns and which operations it should provide.

A release object might store a title and status while offering an operation to submit it for review. Not every operation should directly change every field. The design should preserve meaningful conditions, such as preventing publication before required information is complete. These conditions become part of the object’s contract.

Further reading: Java classes and objects

2. Encapsulation and constructors

Encapsulation places implementation details behind a controlled interface. Making fields private is useful when public methods preserve valid state, but secrecy alone is not the goal. A constructor establishes an object’s initial state. Validate requirements at appropriate boundaries and make failure understandable.

If a class exposes a mutable internal collection directly, callers may bypass its rules even though the field itself is private. Think about ownership, copying, and permitted mutation. A good interface expresses what the component promises while allowing its internal representation to change without breaking every caller.

Further reading: Java object-oriented concepts

3. Interfaces, inheritance, and polymorphism

An interface describes a contract that different implementations can satisfy. Polymorphism allows code to work through a shared abstraction while actual behaviour depends on the implementation. Inheritance can reuse or specialise behaviour, but it also creates a relationship that must respect the superclass’s expectations.

Composition builds a component from other components and can provide flexibility without forcing an unsuitable inheritance hierarchy. Choose inheritance for a defensible substitutable relationship, not merely because two classes share fields. A payment-processing interface may permit several providers without requiring their internal data to match.

Further reading: Java object-oriented concepts

4. Exceptions, testing, and a lab sequence

Exceptions represent abnormal conditions that cannot be handled by the normal path under the chosen design. Catch them where a meaningful response is possible rather than silently hiding them. Distinguish invalid input, unavailable resources, and programming errors. Tests should verify contracts, boundary values, and important state transitions.

A useful lab sequence builds a small class, validates construction, adds an interface, creates two implementations, and tests polymorphic calls. Trace references and object state by hand. Explain what remains stable at the interface and what differs inside each implementation. More classes do not automatically mean better design.

Further reading: Java object-oriented concepts

Applied business–computing case: reason, implement and review

Design a small order model with product, order line and order responsibilities. Encapsulation keeps valid state changes behind clear methods instead of allowing arbitrary modification. An order line should not accept an invalid quantity merely because its field is numeric. Define invariants and enforce them where state changes occur.

Prefer a design that makes responsibilities understandable over one that demonstrates every language feature. Inheritance can be useful when the relationship is appropriate; composition may better express cooperation between independent parts. Test creation, modification and rejected input. Explain how the model connects to persistence and transaction rules: an in-memory object does not by itself prevent two users reserving the same stock. Object-oriented design supports maintainable code, while business correctness requires the broader system context.

Specify a release object before implementing it

Design a Release with title, a privately owned list of tracks and a state such as draft, submitted or approved. Write contracts for adding a track, submitting and approving. Submission should reject an empty title or empty track list; approval should require prior submission. Give each invalid transition an explicit expected response. Trace one valid sequence and attempts to approve a draft or modify a returned internal collection.

Compare returning the mutable internal track list with returning a defensive representation that callers cannot use to bypass the release's rules. Explain how the representation affects ownership, not merely field visibility. Specify a ReviewPolicy interface and two hypothetical implementations with different review conditions. A caller should depend on the contract, while implementation details vary. Do not assume shared fields establish a valid inheritance relationship.

Undergraduates should distinguish class, instance, reference and state using the traces. Postgraduates should compare composition with inheritance through substitutability and change requirements. Research learners should formulate an invariant and evaluate whether each public operation preserves it. Deliver pseudocode, contracts and expected test cases; report compilation or test results only if implementation was actually run. For retention, explain why catching every exception and continuing could leave the caller believing an invalid transition succeeded.

Study questions and answers

What is the difference between class and object?

A class defines a type’s structure and behaviour; an object is a particular instance with its own state.

Why is inheritance not always the best way to reuse code?

It creates a substitutability relationship that may not fit the model. Composition can reuse behaviour with less coupling.

Extended practice questions

Explain encapsulation using an order object, without assuming that private fields alone guarantee valid orders.

Encapsulation groups related state and behaviour behind an intended interface. An order can expose operations that add an accepted line or calculate a total while protecting internal representation from arbitrary changes. The operations must enforce relevant invariants, such as valid quantities, rather than simply conceal fields. A private negative quantity remains a bad state if a method permits it. Object design supports consistency and change management, but business definitions and authorisation need separate reasoning. Decide what the object represents and which transitions are valid before treating the class as a faithful business model.

Marking guide: State/behaviour/interface; invariants; privatefield limit; business representation. Indicative allocation: reasoning 4; application or workings 3; assumptions and limits 3.

Marks: 10

An order contains two units at ₹150 and three at ₹100. Calculate its subtotal before discounts and other charges; specify one validation case.

The first line contributes two times ₹150, or ₹300. The second contributes three times ₹100, also ₹300. Subtotal is ₹600 before discounts, taxes, shipping and other excluded charges. One validation case is a proposed negative quantity: the operation should reject or explicitly model it according to the defined business meaning, rather than silently subtracting from the order. Returns may require a separate authorised process. A total-calculation method should use a suitable money representation and specified rounding rules in real software; this integer-valued illustration does not define the complete implementation.

Marking guide: 600; excludedcharges; negativequantity semantics; monetary/rounding scope. Indicative allocation: reasoning 4; application or workings 3; assumptions and limits 3.

Marks: 10

Critique creating one subclass for every possible customer category.

Inheritance can express a genuine substitutable relationship, but multiplying subclasses for combinations of pricing, region and service preferences can make change difficult. Consider whether these are independent policies or data rather than fundamentally different object types. Composition can combine behaviours while retaining a simpler identity model. Examine the operations clients expect and test whether substitutions preserve their promises. A hierarchy diagram may look organised while encoding accidental business labels. The design choice should follow stable behaviour and maintainability needs, not the assumption that every marketing segment needs a new class.

Marking guide: Substitution; combinatorial variation; composition/data; stablebehaviour; diagramlimit. Indicative allocation: reasoning 4; application or workings 3; assumptions and limits 3.

Marks: 10

Design research on object-model clarity and maintenance effort.

Compare programmers maintaining equivalent business tasks under alternative object designs, with the changes and acceptance tests defined in advance. Measure correct completion, revision effort and explanation of invariants rather than counting classes alone. Record experience and familiarity with each design. Interview participants about where the model supports or obscures business meaning. The contribution could identify representation choices that improve reasoning under specified changes. It should not claim that fewer classes always mean better software or that a toy example establishes performance for a production enterprise system.

Marking guide: Equivalenttask/tests; correctness/effort; experience; meaning; transferlimits. Indicative allocation: reasoning 4; application or workings 3; assumptions and limits 3.

Marks: 10

An order object's amount can be changed directly to a negative value. What design issue should be addressed?

Unrestricted mutable state allows callers to bypass the object's intended invariant. Encapsulate the amount and expose an operation that validates the proposed change under the stated business rule. Validate construction as well as later updates, and define how invalid requests are reported. Encapsulation supports a consistent object contract but does not replace server authorisation or database constraints. The business owner defines whether negative values represent valid refunds or invalid order amounts. A field being private is a design mechanism, not proof that every path preserves the invariant.

Marking guide: State/invariant; validated construction/update; business meaning; security/database distinction. Indicative allocation:reasoning4;application or workings3;assumptions and limits3.

Marks: 10

Compare a class, an object and an interface using payment processing.

A class defines a type's implemented state and behaviour, such as a particular payment processor. An object is an instance with its own state and runtime identity. An interface specifies a contract that different implementing types can satisfy, allowing callers to depend on required operations rather than one implementation. This supports substituting a test implementation or a different provider when contracts are compatible. It does not guarantee identical business behaviour or make remote failures disappear. Specify outcomes, errors and side effects as part of the practical contract, not merely method names.

Marking guide: Definition/instance/contract; substitution; outcome/error/side-effect limits. Indicative allocation:reasoning4;application or workings3;assumptions and limits3.

Marks: 10

Two order objects begin with quantities 2 and 5. Updating the first to3 should leave the second at what quantity, assuming quantity is an instance field?

The second should remain 5 because each object owns its instance-field state. The first becomes 3. If quantity were mistakenly shared as static state, changing it could affect behaviour across instances and violate the intended model. Trace both objects before and after the update and test their independence. The example assumes no deliberate shared backing record or alias to the same object. Object identity and storage design matter when several references or users manipulate business records; a simple two-instance test does not establish concurrency safety in a deployed application.

Marking guide: Second 5;first 3;instance/static distinction;identity/shared-record and concurrency caveats. Indicative allocation:reasoning4;application or workings3;assumptions and limits3.

Marks: 10

Specify tests for an order class and a replaceable payment interface.

Test valid construction, invalid amounts, permitted state changes and independence between instances. Use a controlled payment implementation to exercise success, rejection and failure without sending real money. Define what happens if a request is repeated and whether payment and order updates require coordinated handling. Check the observable contract rather than only internal field assignments. Developers maintain type and error behaviour; finance validates transaction meaning. These tests assess the teaching implementation, not a real provider's reliability, account permissions or production transaction safety.

Marking guide: Construction/invariants; instance independence; controlled success/failure; repeat semantics; scope. Indicative allocation:reasoning4;application or workings3;assumptions and limits3.

Marks: 10

Revision cards

Explain encapsulation using an order object, without assuming that private fields alone guarantee valid orders.

Encapsulation controls state through an interface; methods still need to enforce valid business transitions and invariants.

An order contains two units at ₹150 and three at ₹100. Calculate its subtotal before discounts and other charges; specify one validation case.

Subtotal is ₹600; validate quantity meaning and define separate authorised handling of returns and other charges.

An order object's amount can be changed directly to a negative value. What design issue should be addressed?

Encapsulate state and validate every permitted change. Private fields help enforce an invariant but do not replace business definitions or security controls.

Compare a class, an object and an interface using payment processing.

Class:implemented type; object:instance; interface:contract. Interchangeable method names still need compatible outcomes, errors and side effects.

Two order objects begin with quantities 2 and 5. Updating the first to3 should leave the second at what quantity, assuming quantity is an instance field?

Second quantity stays 5; first becomes 3. Instance state is separate unless the design deliberately shares an object or backing record.

Specify tests for an order class and a replaceable payment interface.

Test invariants, separate instances and controlled payment outcomes, including repeats and failure. A test implementation must not send real money.

What does encapsulation protect in an order object?

It keeps state changes behind defined operations that enforce invariants, such as preventing invalid quantities. Private fields alone are insufficient if public methods allow inconsistent updates or expose mutable internal state.

Why prefer a clear interface over exposing implementation details?

Callers depend on an agreed behaviour rather than internal storage choices. This supports controlled change and testing. The interface still needs explicit failure conditions and cannot hide business assumptions that callers must understand.

Practice task

Create an interface for a notification service and two implementations. Test a caller that uses the interface, then explain how encapsulation and substitution affect the design.

Sources and further reading

  • Java classes and objects
    Type: Free learning material; no paid certificate required
    Use: Official free Java learning material.
  • Java object-oriented concepts
    Type: Free learning material; no paid certificate required
    Use: Study interfaces, inheritance, and object modelling.

Related courses

Open interactive reading and progress tools