[Go to site: main page, start]

0% found this document useful (0 votes)
14 views3 pages

Java OOP Concepts with Examples

The document provides examples of key Object-Oriented Programming (OOP) concepts in Java, including classes and objects, encapsulation, inheritance, polymorphism (both overriding and overloading), abstraction, and interfaces. Each concept is illustrated with code snippets demonstrating their implementation and functionality. The examples cover various scenarios such as creating a Car class, managing a BankAccount, and using interfaces for multiple behaviors.

Uploaded by

binduann
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views3 pages

Java OOP Concepts with Examples

The document provides examples of key Object-Oriented Programming (OOP) concepts in Java, including classes and objects, encapsulation, inheritance, polymorphism (both overriding and overloading), abstraction, and interfaces. Each concept is illustrated with code snippets demonstrating their implementation and functionality. The examples cover various scenarios such as creating a Car class, managing a BankAccount, and using interfaces for multiple behaviors.

Uploaded by

binduann
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1.

Class & Object


Example: Creating a simple Car class.

class Car {
String model;
int year;

void displayInfo() {
[Link]("Model: " + model + ", Year: " + year);
}
}

public class Main {


public static void main(String[] args) {
Car myCar = new Car(); // Object
[Link] = "Toyota";
[Link] = 2020;
[Link](); // Output: Model: Toyota, Year: 2020
}
}

2. Encapsulation
Example: Protecting balance in a BankAccount class.

class BankAccount {
private double balance; // private = encapsulated

public void deposit(double amount) {


if (amount > 0) balance += amount;
}

public double getBalance() {


return balance;
}
}

public class Main {


public static void main(String[] args) {
BankAccount acc = new BankAccount();
[Link](1500);
[Link]("Balance: " + [Link]());
}
}

3. Inheritance
Example: Dog inherits from Animal.

class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}

class Dog extends Animal {


void bark() {
[Link]("Dog barks");
}
}

public class Main {


public static void main(String[] args) {
Dog d = new Dog();
[Link](); // Inherited method
[Link](); // Dog's own method
}
}

4. Polymorphism - Overriding
Method Overriding (Runtime Polymorphism)

class Animal {
void sound() {
[Link]("Generic animal sound");
}
}

class Cat extends Animal {


void sound() {
[Link]("Meow");
}
}

public class Main {


public static void main(String[] args) {
Animal a = new Cat(); // Polymorphic reference
[Link](); // Output: Meow
}
}

4. Polymorphism - Overloading
Method Overloading (Compile-time Polymorphism)

class Calculator {
int add(int a, int b) {
return a + b;
}

double add(double a, double b) {


return a + b;
}
}

public class Main {


public static void main(String[] args) {
Calculator c = new Calculator();
[Link]([Link](2, 3)); // 5
[Link]([Link](2.5, 4.5)); // 7.0
}
}

5. Abstraction
Example: Abstract Shape class.

abstract class Shape {


abstract void draw();
}

class Circle extends Shape {


void draw() {
[Link]("Drawing a circle");
}
}

public class Main {


public static void main(String[] args) {
Shape s = new Circle();
[Link](); // Output: Drawing a circle
}
}

6. Interface
Example: Using interface for multiple behaviors.

interface Printable {
void print();
}

class Document implements Printable {


public void print() {
[Link]("Printing document...");
}
}

public class Main {


public static void main(String[] args) {
Printable p = new Document();
[Link](); // Output: Printing document...
}
}

Common questions

Powered by AI

Using a polymorphic reference allows the variable of a superclass type (Animal) to refer to objects of its subclass type (Cat). This mechanism enables flexible code where specific subclass behaviors (e.g., Cat's sound()) can be invoked through a superclass reference. It promotes code extensibility and reuse as new subclasses can be introduced without modifying existing references. However, direct access to subclass-specific methods is not allowed without casting, which can add some complexity .

Method overloading enables multiple methods in the same class to have the same name with different parameters, facilitating compile-time polymorphism and enhancing method usability across different data types. Method overriding, part of runtime polymorphism, allows a subclass to provide its specific implementation of a method defined in its superclass, enabling dynamic method resolution based on object type. While overloading improves flexibility and code readability, overriding supports extension and modification of behaviors in derived classes while maintaining a consistent interface .

In a banking application, inheritance can facilitate hierarchical relationships among account types, such as a superclass Account with subclasses SavingsAccount and CheckingAccount, enabling shared functionality like balance operations with specific withdrawal rules. Interfaces can define behaviors such as ITransactional with methods like executeTransaction(), implemented by classes handling different transaction types like Deposit and Withdrawal. This design allows for account type extensions, while interface-based transaction classes provide flexibility and adherence to multiple behavior contracts across the application .

Interfaces enable multiple inheritance by allowing a class like Document to implement multiple interfaces such as Printable. This capability allows a class to conform to multiple contracts while maintaining separate method implementations for each contract. This multiple inheritance feature addresses the limitations of class-based inheritance in Java, where a class can only extend one superclass, thus promoting more flexible and modular design .

Encapsulation protects the BankAccount class's data by restricting access to the private balance variable. Direct access to balance is not allowed from outside the class, thus preserving its integrity. The balance variable is only accessible through public methods such as deposit() and getBalance(), which include logic to validate changes and check access, enhancing data security .

Abstract classes like Shape offer a blueprint for derived classes, which can help enforce a consistent method interface across different implementations and promote code reuse. They facilitate abstraction by allowing developers to handle classes at a more generic level. However, they can be less flexible than interfaces if multiple inheritance is needed, as Java does not support multiple class inheritance. Abstract classes are useful when both default behavior and consistent interface enforcement are required .

Method overloading improves code readability and usability by allowing different methods to perform similar functions on different types or numbers of inputs. In the Calculator class, having overloaded methods for add() facilitates operations on both integers and doubles without requiring separate method names, enhancing intuitive use and maintainability. It reduces method name redundancy while ensuring type safety during compile-time .

Abstraction in software development, as exemplified by the abstract Shape class, simplifies complex systems by focusing only on essential characteristics while hiding details that are irrelevant to the current context. This reduction of complexity allows developers to manage and optimize systems without being overwhelmed by intricate details. However, poorly executed abstraction can lead to overly generic interfaces that may not adequately fit specific applications, complicating maintenance and expansion. Thus, careful design of abstractions is crucial to leverage their full benefits .

Inheritance allows subclasses to inherit methods from a superclass, enabling objects to be treated as instances of their parent class. Polymorphism is achieved through method overriding, where a subclass like Cat can provide a specific implementation of a method, sound(), that is present in its superclass, Animal. At runtime, the overridden method gets called based on the object type, not the reference type, demonstrating runtime polymorphism .

Encapsulation ensures the integrity and consistency of a class's data by restricting direct access to its fields, such as the balance in BankAccount. By providing controlled access through methods like deposit() and getBalance(), encapsulation confines data modification and retrieval within well-defined boundaries, preventing unauthorized alterations. This mechanism ensures that balance integrity is maintained by allowing only validated updates and consistent data exposure through defined interfaces .

You might also like