Java Classes, Methods, and Functions Overview
1. Java Classes
- A class in Java is a blueprint from which individual objects are created.
- Syntax:
public class ClassName {
// fields
// methods
- Example:
public class Car {
String color;
void drive() {
System.out.println("Car is driving");
2. Constructors
- Special method that is called when an object is instantiated.
- Name of constructor = class name. No return type.
- Types:
a) Default constructor
b) Parameterized constructor
- Example:
public Car(String model) {
this.model = model;
3. Methods
Java Classes, Methods, and Functions Overview
- A method is a block of code which only runs when it is called.
- Syntax:
returnType methodName(parameters) {
// code
- Example:
public int add(int a, int b) {
return a + b;
4. Static Methods
- Belong to the class rather than instances.
- Can be called without creating an object.
- Example:
public static void display() {
System.out.println("Static Method");
5. Overloading and Overriding
- Method Overloading: Same method name, different parameters.
- Method Overriding: Subclass provides specific implementation of superclass method.
- Example Overload:
int add(int a, int b)
int add(int a, int b, int c)
- Example Override:
class Animal { void sound() {} }
class Dog extends Animal { void sound() { System.out.println("Bark"); } }
Java Classes, Methods, and Functions Overview
6. Common Built-in Classes
- String: string manipulation
- Math: math functions (abs, pow, sqrt)
- Scanner: user input
- ArrayList: dynamic arrays
- HashMap: key-value pair storage
- File: file operations
7. Access Modifiers
- public: accessible everywhere
- private: accessible within class only
- protected: accessible in same package or subclass
- default: accessible in same package
8. Final, Abstract and Interface
- final: constant or non-overridable
- abstract: class or method not fully implemented
- interface: blueprint for classes (all methods abstract by default)
- Example Interface:
interface Animal {
void makeSound();