Category : Java | Sub Category : Object- oriented Programming | By Prasad Bonam Last updated: 2023-07-31 06:28:03 Viewed : 70
Object-Oriented Programming (OOP) is a programming paradigm that focuses on organizing code into objects, which encapsulate data and behavior. Java is an object-oriented programming language, and it follows several OOP principles. Here are the main OOP concepts in Java:
javaclass MyClass {
// Properties (attributes)
int myInt;
String myString;
// Constructor
public MyClass(int myInt, String myString) {
this.myInt = myInt;
this.myString = myString;
}
// Method
public void printInfo() {
System.out.println("MyInt: " + myInt + ", MyString: " + myString);
}
}
new
keyword. It represents a real-world entity and has its own state and behavior.javaMyClass myObject = new MyClass(42, "Hello");
javaclass BankAccount {
private double balance;
// Getter and Setter methods
public double getBalance() {
return balance;
}
public void setBalance(double newBalance) {
if (newBalance >= 0) {
balance = newBalance;
}
}
}
javaclass Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
// Inherits sound() method from Animal class
}
javaclass MathOperations {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
javaclass Shape {
void draw() {
System.out.println("Drawing a shape");
}
}
class Circle extends Shape {
@Override
void draw() {
System.out.println("Drawing a circle");
}
}
javaabstract class Shape {
// Abstract method (no implementation)
abstract void draw();
// Concrete method (with implementation)
void displayInfo() {
System.out.println("This is a shape.");
}
}
Association: A simple relationship between objects, where one object knows about the other.
Aggregation: A stronger relationship where one object contains another object, but they can exist independently.
Composition: A stronger form of aggregation where one object is composed of other objects, and they cannot exist independently.
These are the core OOP concepts in Java. Understanding and applying these concepts properly can lead to more organized, maintainable, and scalable code.