Java Concepts Explained With Programs
Java Concepts Explained With Programs
Programs
2. Static Data Members and Functions
In Java, static data members (variables) belong to the class rather than instances (objects)
of the class.
This means all objects of the class share the same copy of the static data member. Static
functions
(or methods) can be called without creating an object of the class, and they can only access
static data members.
Static data members are useful for shared properties or behaviors of all objects of a class.
For example, keeping a count of the number of objects created. Static methods are used
when an action is
not dependent on object-specific data.
Program Example
class StaticExample {
static int count = 0;
StaticExample() {
count++;
}
Function overloading in Java occurs when multiple methods in the same class have the same
name but different parameters.
Java does not support operator overloading as in C++, but some operators like "+" are
overloaded internally for String concatenation.
Function overloading improves code readability and allows a method to handle different
types or numbers of inputs.
In Java, overloaded "+" for strings makes it easy to combine text.
Program Example
class OverloadingExample {
void display(int a) {
System.out.println("Integer: " + a);
}
void display(String a) {
System.out.println("String: " + a);
}
Program Example
class Animal {
void makeSound() {
System.out.println("Animal sound");
}
}
class Owner {
Dog pet;
Owner(Dog pet) {
this.pet = pet;
}
void playWithPet() {
pet.makeSound();
}
5. Composition
Composition is a strong "has-a" relationship where one class contains another class as a
part of its body.
In composition, the lifespan of the contained object depends on the lifespan of the
containing object.
Composition is used when one object is made up of one or more smaller objects. If the
containing object is destroyed,
so are the contained objects. It ensures better encapsulation and modularity in object-
oriented design.
Program Example
class Engine {
void start() {
System.out.println("Engine started");
}
}
class Car {
private Engine engine;
Car() {
engine = new Engine();
}
void startCar() {
engine.start();
System.out.println("Car started");
}
6. Aggregation
Aggregation is a weaker form of a "has-a" relationship where the contained object can exist
independently of the container.
For example, a library can have multiple books, but a book can exist outside of the library.
Aggregation is used when the relationship between classes is loose and the lifetime of the
contained object is independent of the container.
It provides flexibility in object management and reuse.
Program Example
class Book {
String title;
Book(String title) {
this.title = title;
}
String getTitle() {
return title;
}
}
class Library {
List<Book> books = new ArrayList<>();
void displayBooks() {
for (Book book : books) {
System.out.println("Book: " + book.getTitle());
}
}