пятница, 5 января 2024 г.

Aggregation in Java

    Aggregation is another relationship between classes in object-oriented programming. In aggregation, one class contains an object of another class, but the contained object can exist independently of the class that contains it. Aggregation represents a "has-a" relationship, where one class has another class as a part.

In Java, aggregation is typically implemented by creating a member variable in one class that refers to an object of another class. The object can be created, modified, and destroyed independently of the containing class. The "aggregated" class is not a part of the "container" class in the same way that subclasses are part of their superclasses in inheritance.

Here's a simple example to illustrate aggregation:

// Aggregated class
class Engine {
private String type;

public Engine(String type) {
this.type = type;
}

public String getType() {
return type;
}
}

// Container class using aggregation
class Car {
private String model;
private Engine engine; // Aggregation: Car has an Engine

public Car(String model, Engine engine) {
this.model = model;
this.engine = engine;
}

public String getModel() {
return model;
}

public Engine getEngine() {
return engine;
}
}

public class AggregationExample {
public static void main(String[] args) {
// Creating an instance of the aggregated class (Engine)
Engine carEngine = new Engine("V6");

// Creating an instance of the container class (Car) with the aggregated class
Car myCar = new Car("Sedan", carEngine);

// Accessing properties using aggregation
System.out.println("Car Model: " + myCar.getModel());
System.out.println("Engine Type: " + myCar.getEngine().getType());
}
}

Inheritance in Java

    Inheritance is a fundamental concept in object-oriented programming (OOP) languages like Java. It allows a class to inherit properties and behaviors (fields and methods) from another class, promoting code reuse and establishing a relationship between classes. In Java, the "extends" keyword is used to implement inheritance.

In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is called child or subclass.

Here's a basic example to illustrate inheritance in Java:

// Parent class (also called superclass)
class Animal {
String name;

public Animal(String name) {
this.name = name;
}

public void eat() {
System.out.println(name + " is eating.");
}

public void sleep() {
System.out.println(name + " is sleeping.");
}
}

// Child class (also called subclass)
class Dog extends Animal {
public Dog(String name) {
// Call the constructor of the superclass (Animal)
super(name);
}

public void bark() {
System.out.println(name + " is barking.");
}
}

public class InheritanceExample {
public static void main(String[] args) {
// Creating an instance of the Dog class
Dog myDog = new Dog("Buddy");

// Accessing methods from the superclass (Animal)
myDog.eat();
myDog.sleep();

// Accessing methods from the subclass (Dog)
myDog.bark();
}
}

Keep in mind that Java supports single inheritance, meaning a class can only extend one superclass. However, it can implement multiple interfaces to achieve a form of multiple inheritance.


Method overloading in Java

    Method overloading in Java allows a class to have multiple methods with the same name, but with different parameter lists. It provides a way to define multiple methods within the same class that perform similar tasks but with variations in the type or number of parameters.

Here are the key rules and considerations for method overloading in Java:

  • Method Signature:

Methods must have the same name but different parameter lists. The parameter lists can differ in terms of the number of parameters, types of parameters, or both.

  • Return Type:
The return type of the methods can be the same or different. Method overloading is not based on the return type.

  • Access Modifiers:
Access modifiers (public, private, protected) can be the same or different for overloaded methods.

  • Exceptions:
Method overloading can include methods with different exception types or the same exception types.

public class Calculator {
// Method with two int parameters
public int add(int a, int b) {
return a + b;
}
// Method with three int parameters
public int add(int a, int b, int c) {
return a + b + c;
}
// Method with two double parameters
public double add(double a, double b) {
return a + b;
}
// Method with a different parameter type (String)
public String add(String a, String b) {
return a + b;
}

public static void main(String[] args) {
Calculator calculator = new Calculator();
        // Calls the first method
System.out.println(calculator.add(2, 3));
        // Calls the second method
System.out.println(calculator.add(2, 3, 4));
        // Calls the third method
System.out.println(calculator.add(2.5, 3.5));
        // Calls the fourth method
System.out.println(calculator.add("Hello", "World"));
}
}

Access Modifiers in Java

Access modifiers control the visibility of classes, fields, methods, and constructors. Java has four levels:


1. public

Accessible from anywhere — any class, in any package.

public class Car {
public String model;
public void drive() { }
}

2. protected

Accessible within the same package, plus subclasses in other packages (via inheritance).

class Animal {
protected String name;
protected void makeSound() { }
}


3. default (no modifier)

Accessible only within the same package. If you don't write any modifier, this is what you get.

class Utility {
int helperValue; // default access
void helperMethod() { } // default access
}


4. private

Accessible only within the same class. Not visible to subclasses or anything outside.

class BankAccount {
private double balance;
private void logTransaction() { }
}


Where They Apply

  • Top-level classes/interfaces: only public or default (no private/protected)
  • Members (fields, methods, constructors, nested classes): all four modifiers apply

this keyword in Java

    The 'this' keyword is a reference variable that refers to the current object. It can be used to refer to the instance variables of the current object, invoke the current object's methods and differentiate instance variables from local variables when they have the same name.

Here are some key uses of the this keyword in Java:

  • To refer to instance variables:
  When there is a need to differ between instance variables and local variables with the same name, you can use 'this' to refer to the instance variables.

public class MyClass {
private int x;

public void setX(int x) {
// Use "this" to refer to the instance variable
this.x = x;
}
}


  • To invoke the current object's method:
You can use 'this' to invoke the current object's method. This is often seen in constructors to call another constructor of the same class.

public class MyClass {
private int x;

public MyClass() {
// Call the parameterized constructor using "this"
this(0);
}

public MyClass(int x) {
this.x = x;
}
}


  • To pass the current object as a parameter to other methods:
When you need to pass the current object as a parameter to other methods, you can use 'this'.

public class MyClass {
private int x;

public void myMethod() {
// Pass the current object as a parameter
anotherMethod(this);
}

public void anotherMethod(MyClass obj) {
// Do something with the passed object
}
}


  • In constructors to call another constructor:
Already mentioned, but worth highlighting. this() is used to invoke another constructor from the same class.

public class MyClass {
private int x;

public MyClass() {
// Call another constructor with a parameter
this(0);
}

public MyClass(int x) {
this.x = x;
}
}

Objects and Classes in Java

     A class is a blueprint or a template for creating objects. It defines the properties and behaviors that objects of the class will have. An object, on the other hand, is an instance of a class. Objects are created based on the structure defined by the class.

// Defining a class
public class Car {
// Properties or fields
String brand;
String model;
int year;

// Constructor (a special method to initialize objects)
public Car(String brand, String model, int year) {
this.brand = brand;
this.model = model;
this.year = year;
}

// Method (a function associated with the class)
public void displayInfo() {
System.out.println("Brand: " + brand);
System.out.println("Model: " + model);
System.out.println("Year: " + year);
}
}

// Creating objects of the Car class
public class Main {
public static void main(String[] args) {
// Creating two Car objects
Car car1 = new Car("Toyota", "Camry", 2022);
Car car2 = new Car("Honda", "Civic", 2021);

// Calling methods on objects
car1.displayInfo();
System.out.println(); // Adding a line break
car2.displayInfo();
}
}

In this example, we have a class named Car with three properties (brand, model, and year), a constructor to initialize the object, and a method (displayInfo) to display information about the car. In the Main class, we create two instances of the Car class (car1 and car2) and then call the displayInfo method on each of them.

Key concepts related to classes and objects in Java:

  1. Class: A blueprint or template that defines the structure and behavior of objects.
  2. Object: An instance of a class. It is a real-world entity that can be uniquely identified.
  3. Constructor: A special method used for initializing objects. It has the same name as the class and is called when an object is created.
  4. Method: Functions defined within a class that represent the behavior of objects.
  5. Field or Property: Variables that represent the attributes or characteristics of objects.

четверг, 4 января 2024 г.

static keyword in Java

 The 'static' keyword is used to declare elements that belong to the class rather than instances of the class. It can be applied to variables, methods, blocks and nested classes. Here's a brief overview of how 'static' is used in different contexts:


  • Static Variable

  • When a variable is declared as static within a class, it becomes a class variable, also known as a static variable.
  • There is only one copy of a static variable that is shared among all instances of the class.
  • Static variables are typically used for constants or variables that should be common to all instances of a class.
public class Counter {
// Static variable to keep track
// of the number of instances
private static int instanceCount = 0;

// Constructor increments the instance
// count and assigns a unique object number
public Counter() {
instanceCount++;
}

// Static method to get the total number
// of instances created
public static int getInstanceCount() {
return instanceCount;
}

public static void main(String[] args) {
// Creating instances of Counter
Counter obj1 = new Counter();
Counter obj2 = new Counter();
Counter obj3 = new Counter();

// Accessing static method to get the
// total number of instances
System.out.println("Total number of instances: "
+ Counter.getInstanceCount());
}
}

  • Static Methods:

    • When a method is declared as static, it belongs to the class rather than to any particular instance of the class.
    • Static methods can be called using the class name, without creating an instance of the class.
    • Static method can access static data member and can change the value of it.
    public class StaticInitializerExample {
    // Static variable to be initialized
    private static int staticVariable;

    // Static method to initialize the static variable
    public static void initializeStaticVariable(int value) {
    staticVariable = value;
    System.out.println("Static variable initialized to: "
    + staticVariable);
    }

    // Method to get the value of the static variable
    public static int getStaticVariable() {
    return staticVariable;
    }

    public static void main(String[] args) {
    // Calling the static method to initialize
    // the static variable
    StaticInitializerExample.initializeStaticVariable(42);

    // Accessing the static variable using a static method
    int retrievedValue = StaticInitializerExample.getStaticVariable();
    System.out.println("Retrieved static variable value: "
    + retrievedValue);
    }
    }

    • Static Blocks:

    • Static blocks are used to initialize static variables.
    • They are executed only once when the class is loaded into memory.
    public class StaticBlockExample {
    // Static variable to be initialized
    private static int staticVariable;

    // Static block to initialize the static variable
    static {
    staticVariable = 42;
    System.out.println("Static variable initialized in the static block: "
    + staticVariable);
    }

    // Method to get the value of the static variable
    public static int getStaticVariable() {
    return staticVariable;
    }

    public static void main(String[] args) {
    // Accessing the static variable using a static method
    int retrievedValue = StaticBlockExample.getStaticVariable();
    System.out.println("Retrieved static variable value: " + retrievedValue);
    }
    }

    • Static Nested Classes
    • A static nested class is a nested class that is declared as static.
    • It can be accessed using the class name without creating an instance of the outer class
    public class OuterClass {
    // Instance variable of the outer class
    private int outerVar;

    // Constructor for the outer class
    public OuterClass(int outerVar) {
    this.outerVar = outerVar;
    }

    // Instance method of the outer class
    public void outerMethod() {
    System.out.println("Outer Method");
    }

    // Static nested class
    public static class StaticNestedClass {
    // Static nested class can have its own members
    private int nestedVar;

    // Constructor for the static nested class
    public StaticNestedClass(int nestedVar) {
    this.nestedVar = nestedVar;
    }

    // Method of the static nested class
    public void nestedMethod() {
    System.out.println("Nested Method");
    }
    }
    }


    public class Main {
    public static void main(String[] args) {
    // Creating an instance of the outer class
    OuterClass outerInstance = new OuterClass(10);

    // Accessing instance members of the outer class
    outerInstance.outerMethod();

    // Creating an instance of the static nested class
    // without an instance of the outer class
    OuterClass.StaticNestedClass nestedInstance =
    new OuterClass.StaticNestedClass(5);

    // Accessing members of the static nested class
    nestedInstance.nestedMethod();
    }
    }