Java Programming Essentials: OOP and Core Syntax
Java Program Structure
A typical Java application is composed of one or more classes. The most basic structure for a runnable Java program includes:
- Package Declaration (Optional): Specifies the package the class belongs to.
package com.example.app; - Import Statements (Optional): Allows using classes from other packages (like built-in Java libraries).
import java.util.Scanner; - Class Definition: Defines the main structure of the program.
public class MyProgram { // ... Class body ... } - main Method (For Executable Programs): The entry point where the Java Virtual Machine (JVM) starts execution.
public static void main(String[] args) { // Program logic goes here }
Classes and Objects (OOP Core)
This is the heart of Object-Oriented Programming (OOP).
Class
A class is a blueprint or a template for creating objects. It defines the characteristics (attributes or fields) and behaviors (methods) that the objects of that type will have.
- Example: A class named Car might define attributes like color and speed, and methods like startEngine() and brake().
Object
An object is a runtime instance of a class. When you create an object, you allocate memory for it, and it possesses the attributes and behaviors defined by its class.
- Example:
Car redCar = new Car();creates an object named redCar that is an instance of the Car class.
Key OOP Concepts
- Encapsulation: Binding data (attributes) and methods that operate on the data into a single unit (the class). This is often achieved by making attributes private and providing public access methods (getters and setters).
- Inheritance: A mechanism where one class (subclass) inherits the fields and methods of another class (superclass).
- Polymorphism: The ability of an object to take on many forms, often demonstrated through method overriding and interface implementation.
Data Types in Java
Java is a statically typed language, meaning all variables must be declared with a specific type before they can be used. Java has two main categories of data types:
1. Primitive Data Types
These hold simple, single values and are predefined by Java. They include:
| Type | Size (Bytes) | Range/Purpose | Example |
|---|---|---|---|
| boolean | 1 | Represents truth values (true/false). | boolean isValid = true; |
| byte | 1 | Small integer. | byte b = 10; |
| short | 2 | Short integer. | short s = 1000; |
| int | 4 | Standard integer (most common). | int age = 30; |
| long | 8 | Large integer. | long population = 7000000000L; |
| float | 4 | Single-precision floating-point number. | float pi = 3.14f; |
| double | 8 | Double-precision floating-point number (most common). | double price = 19.99; |
| char | 2 | Single Unicode character. | char grade = 'A'; |
2. Non-Primitive (Reference) Data Types
These don’t hold the values directly but hold references (memory addresses) to the objects. Examples include String, Arrays, and Classes (like Car, Scanner, etc.).
Type Casting
Type casting is the process of converting a value from one data type to another.
Widening/Implicit Casting (Automatic)
Converting a smaller type to a larger type. This is safe and happens automatically.
- Order: byte → short → char → int → long → float → double
- Example:
int myInt = 9;double myDouble = myInt; // Automatic casting (myDouble is 9.0)
Narrowing/Explicit Casting (Manual)
Converting a larger type to a smaller type. This might result in a loss of data or precision, so it requires you to explicitly use parentheses with the target type.
- Example:
double myDouble = 9.78;int myInt = (int) myDouble; // Manual casting (myInt is 9)
Looping Constructs
Loops are used to execute a block of code repeatedly as long as a certain condition is met.
1. for Loop
Used when you know exactly how many times you want to loop.
for (initialization; condition; update) {
// code to be executed repeatedly
}- Example (printing 1 to 5):
for (int i = 1; i <= 5; i++) { System.out.println(i); }
2. Enhanced for Loop (for-each)
Used for iterating over arrays and collections (like ArrayLists).
for (dataType element : arrayOrCollection) {
// code using the element
}- Example (iterating an array):
String[] names = {"Alice", "Bob"};for (String name : names) { System.out.println(name); }
3. while Loop
Used when you don’t know the exact number of iterations, but the loop continues as long as a condition remains true. The condition is checked before the loop body executes.
while (condition) {
// code to be executed
}4. do-while Loop
Similar to while, but the condition is checked after the loop body executes. This ensures the loop body runs at least once.
do {
// code to be executed
} while (condition);Interface Basics
In object-oriented programming (OOP), particularly in languages like Java, an interface is a reference type that is conceptually similar to a class, but it defines a contract for behavior. It outlines what a class must do without specifying how it does it. This is a crucial concept for achieving abstraction and polymorphism.
Key Characteristics of an Interface
- Blueprint of a Class: An interface is a template that specifies a set of methods that any class implementing it must provide.
- Abstraction: Interfaces are 100% abstract, meaning they cannot be instantiated (you cannot create an object directly from an interface).
- Methods: Traditionally, interfaces contained only abstract methods (methods without a body). Since Java 8, interfaces can also include:
- Default Methods: Methods with a body, which provide a standard implementation that implementing classes can use or override.
- Static Methods: Utility methods related to the interface, which can be called directly on the interface itself.
- Fields (Variables): Any fields declared within an interface are implicitly public, static, and final (i.e., they are constants). They must be initialized at the time of declaration.
- Keyword: An interface is defined using the
interfacekeyword instead ofclass.
Defining and Using an Interface
A class uses the implements keyword to adopt the contract defined by an interface.
| Action | Keyword | Purpose |
|---|---|---|
| Defining an interface | interface | public interface Drivable { ... } |
| Implementing an interface | implements | public class Car implements Drivable { ... } |
A class can implement multiple interfaces, which is how OOP languages like Java achieve a form of multiple inheritance of behavior (but not state).
Example
// 1. Defining the Interface (The Contract)
public interface Flyable {
int MAX_ALTITUDE = 50000; // Constant: implicitly public static final
void takeOff(); // Abstract Method: implicitly public abstract
void land();
}
// 2. Implementing the Interface (Fulfilling the Contract)
public class Airplane implements Flyable {
@Override
public void takeOff() {
System.out.println("Airplane taking off.");
}
@Override
public void land() {
System.out.println("Airplane landing.");
}
}Defining, Implementing, and Extending Interfaces
Interfaces are fundamental in object-oriented programming for establishing a contract that classes must adhere to. Here is a breakdown of the three core actions: Defining, Implementing, and Extending.
1. Defining an Interface (The Contract)
You define an interface using the interface keyword. It specifies a set of methods that a class must implement and can also declare constants.
- Syntax:
public interface Shape { double PI = 3.14159; // Constants: implicitly public static final double calculateArea(); // Abstract Methods: implicitly public abstract void draw(); } - Key Rules:
- Methods without a body are abstract and are the core of the contract.
- Fields are constants and cannot be changed by the implementing class.
2. Implementing an Interface (Fulfilling the Contract)
A class uses the implements keyword to adopt the contract of an interface. The implementing class must provide a concrete body for every abstract method defined in the interface.
- Syntax:
public class Circle implements Shape { private double radius; public Circle(double r) { this.radius = r; } @Override public double calculateArea() { return PI * radius * radius; } @Override public void draw() { System.out.println("Drawing a circle with radius: " + this.radius); } } - Key Rules:
- You must use the
implementskeyword. - All implemented methods must be declared as public.
- A class can implement multiple interfaces (e.g.,
class MyClass implements InterfaceA, InterfaceB).
- You must use the
3. Extending Interfaces (Building on Contracts)
Interfaces can extend other interfaces using the extends keyword, allowing you to build a hierarchy of contracts.
- Syntax:
// Shape is the base interface public interface ThreeDShape extends Shape { double calculateVolume(); // Adds a new method to the contract } - Key Rules:
- The extending interface (ThreeDShape) inherits all abstract methods from the base interface (Shape).
- A class that implements ThreeDShape must provide implementations for
calculateArea(),draw()(from Shape), andcalculateVolume()(from ThreeDShape). - An interface can extend multiple other interfaces (e.g.,
interface MySubInterface extends InterfaceA, InterfaceB).
