java practice set (2)
java practice set (2)
1. **Encapsulation**:
```java
public class BankAccount {
// Private attributes
private double balance;
public BankAccount() {
this.balance = 0.0; // Initialize balance to zero
}
}
}
return balance;
}
}
2. **Inheritance**:
- **Definition**: Inheritance is a mechanism where a new class (subclass) derives
properties and behavior (methods) from an existing class (superclass). This feature promotes
code reusability and establishes a hierarchical relationship between classes.
- **Implementation in Java**: In Java, inheritance is implemented using the `extends`
keyword. A subclass can inherit fields and methods from a superclass, and it can also override
methods.
- **Example**:
```java
// Superclass
class Animal {
public void makeSound() {
System.out.println("Animal makes a sound");
}
}
System.out.println("Dog barks");
}
}
```
3. **Polymorphism**:
- **Definition**: Polymorphism allows objects to be treated as instances of their parent
class, enabling a single function to behave differently based on the object it is acting upon.
This can occur through method overriding and overloading.
- **Implementation in Java**: Java supports polymorphism through method overriding
(runtime polymorphism) and method overloading (compile-time polymorphism).
4. **Abstraction**:
- **Definition**: Abstraction is the concept of hiding the complex implementation details
while exposing only the necessary features of an object. It simplifies the interaction with
objects and reduces complexity.
- **Implementation in Java**: Abstraction can be achieved using abstract classes and
interfaces. Abstract classes can have abstract (no implementation) and concrete methods,
while interfaces provide a contract for classes to implement.
### Summary
### Conclusion
In summary, the JDK, JRE, and JVM are interrelated components of the Java
ecosystem, each playing a critical role in the development and execution of Java
applications. The JDK is needed for development, the JRE is required to run
standalone Java applications, and the JVM is the underlying engine that
executes Java bytecode across different platforms. Together, they enable Java's
principle of "Write Once, Run Anywhere" by abstracting the complexities of the
underlying hardware and operating systems.
```java
public class ImplicitCastingExample {
public static void main(String[] args) {
int intVariable = 100; // 4 bytes
long longVariable = intVariable; // Automatically casted to long (8 bytes)
System.out.println("Integer value: " + intVariable);
System.out.println("Long value: " + longVariable);
}
}
```
**Output:**
```
Integer value: 100
Long value: 100
```
In this example, the `int` variable `intVariable` is implicitly cast to a `long` type
when assigned to `longVariable`. The value remains the same, and this
conversion is done automatically by Java.
**Output:**
```
Double value: 9.78
Integer value after explicit casting: 9
```
### Conclusion
Type casting is an essential feature in Java that allows variable type conversions.
Implicit casting automates the process when it is safe to do so, while explicit
casting requires developer intervention due to potential data loss.
Understanding these concepts helps in writing robust and error-free Java
programs, especially when dealing with different numeric types or objects.
```java
// Class to demonstrate access specifiers
class AccessSpecifiersDemo {
// Public field
public String publicField = "Public Field";
// Private field
private String privateField = "Private Field";
// Protected field
protected String protectedField = "Protected Field";
// Private method
private void showPrivateMethod() {
System.out.println("Private Method: " + privateField);
}
// Protected method
protected void showProtectedMethod() {
System.out.println("Protected Method: " + protectedField);
}
- **Public (`public`)**:
- Members declared as public can be accessed from any class in any package. In
the above example, `publicField` and `showPublicMethod()` can be accessed
without restriction.
- **Private (`private`)**:
- Members declared as private are accessible only within the class where they
are defined. Attempting to access `privateField` and `showPrivateMethod()`
from `AccessSpecifiersTest` will result in a compile-time error. This
encapsulation is crucial for data hiding.
- **Protected (`protected`)**:
- Members declared as protected can be accessed within the same package or
by subclasses in different packages. In the example, accessing `protectedField`
and `showProtectedMethod()` is allowed in a subclass. However, because
`AccessSpecifiersTest` is not inheriting `AccessSpecifiersDemo`, it should be
encapsulated to prevent access outside the context defined.
### Conclusion
This program demonstrates how to use and understand Java access specifiers
effectively. By employing the right access levels, developers can achieve better
encapsulation and control over how their classes and methods interact with
other parts of their application.
```java
public class MethodOverloadingDemo {
1. **Method Definitions**:
- The class `MethodOverloadingDemo` contains three overloaded methods
named `add`:
- `add(int a, int b)`: This method takes two `int` parameters and returns their
sum.
- `add(int a, int b, int c)`: This method takes three `int` parameters and
returns their cumulative sum.
- `add(double a, double b)`: This method takes two `double` parameters and
returns their sum as a `double`.
2. **Main Method**:
- An instance of `MethodOverloadingDemo` is created to call these methods.
- `demo.add(5, 10)`: Calls the first overloaded method and computes the sum
of two integers.
- `demo.add(5, 10, 15)`: Calls the second overloaded method and computes
the sum of three integers.
- `demo.add(5.5, 10.5)`: Calls the third overloaded method to compute the
sum of two doubles.
### Output
When you run the program, you will see the following output:
```
Sum of two integers (5 + 10): 15
Sum of three integers (5 + 10 + 15): 30
Sum of two doubles (5.5 + 10.5): 16.0
```
### Conclusion
6. Create a Java class with both static and non-static members. Write a program
to call these members from the main method and explain the difference
between their behavior.