0% found this document useful (0 votes)
2 views12 pages

Java Basics Part4 Classes Objects

This document covers the basics of Java programming, focusing on classes and objects, including class declaration, constructors, access modifiers, static members, inheritance, polymorphism, and interfaces. It also emphasizes OOP principles such as encapsulation, inheritance, polymorphism, and abstraction, along with best practices for coding. Examples of class implementations and method usages are provided to illustrate these concepts.

Uploaded by

Aniket Deshpande
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views12 pages

Java Basics Part4 Classes Objects

This document covers the basics of Java programming, focusing on classes and objects, including class declaration, constructors, access modifiers, static members, inheritance, polymorphism, and interfaces. It also emphasizes OOP principles such as encapsulation, inheritance, polymorphism, and abstraction, along with best practices for coding. Examples of class implementations and method usages are provided to illustrate these concepts.

Uploaded by

Aniket Deshpande
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Java Basics - Part 4: Classes & Objects

Classes & Objects


Class Declaration
public class Person {
// Instance variables (fields)
private String name;
private int age;
private String email;

// Static variable (shared by all instances)


public static int count = 0;

// Final variable (constant)


private final String species = "Human";

// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
count++;
}

// Default constructor
public Person() {
this("Unknown", 0);
}

// Copy constructor
public Person(Person other) {
this.name = other.name;
this.age = other.age;
this.email = other.email;
count++;
}

// Getter methods
public String getName() {
return name;
}

public int getAge() {


return age;
}

1
public String getEmail() {
return email;
}

// Setter methods
public void setName(String name) {
this.name = name;
}

public void setAge(int age) {


if (age >= 0 && age <= 150) {
this.age = age;
}
}

public void setEmail(String email) {


this.email = email;
}

// Instance method
public void introduce() {
System.out.println("Hi, I'm " + name + " and I'm " + age + " years old.");
}

// Static method
public static int getCount() {
return count;
}

// Method with parameters


public void haveBirthday() {
age++;
System.out.println("Happy birthday! You are now " + age + " years old.");
}

// Method returning boolean


public boolean isAdult() {
return age >= 18;
}

// Method with conditional logic


public String getAgeGroup() {
if (age < 13) return "Child";
else if (age < 20) return "Teenager";
else if (age < 65) return "Adult";

2
else return "Senior";
}

// Override toString method


@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + ", email='" + email + "'}";
}

// Override equals method


@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;

Person person = (Person) obj;


return age == person.age &&
Objects.equals(name, person.name) &&
Objects.equals(email, person.email);
}

// Override hashCode method


@Override
public int hashCode() {
return Objects.hash(name, age, email);
}
}

Object Creation and Usage


// Creating objects
Person person1 = new Person("Alice", 25);
Person person2 = new Person("Bob", 30);
Person person3 = new Person(); // Uses default constructor

// Using methods
person1.introduce();
person2.setAge(31);
person3.setName("Charlie");
person3.setAge(22);

// Accessing static members


System.out.println("Total persons: " + Person.getCount());

// Using copy constructor


Person person4 = new Person(person1);

3
// Method chaining (if setters return this)
person1.setName("Alice Smith").setAge(26).setEmail("[email protected]");

Access Modifiers
public class AccessExample {
public String publicField; // Accessible everywhere
protected String protectedField; // Accessible in same package and subclasses
String defaultField; // Accessible in same package only
private String privateField; // Accessible in same class only

public void publicMethod() { }


protected void protectedMethod() { }
void defaultMethod() { }
private void privateMethod() { }
}

// Access levels from most to least restrictive:


// private -> default -> protected -> public

Static Members
public class MathUtils {
// Static constants
public static final double PI = 3.14159;
public static final double E = 2.71828;

// Static variables
private static int operationCount = 0;

// Static methods
public static int add(int a, int b) {
operationCount++;
return a + b;
}

public static double multiply(double a, double b) {


operationCount++;
return a * b;
}

public static int getOperationCount() {


return operationCount;
}

4
// Static initialization block
static {
System.out.println("MathUtils class loaded");
}
}

// Usage
int sum = MathUtils.add(5, 3);
double product = MathUtils.multiply(2.5, 3.0);
System.out.println("PI: " + MathUtils.PI);

Inheritance
// Parent class (superclass)
public class Animal {
protected String name;
protected int age;

public Animal(String name, int age) {


this.name = name;
this.age = age;
}

public void eat() {


System.out.println(name + " is eating");
}

public void sleep() {


System.out.println(name + " is sleeping");
}

public void makeSound() {


System.out.println("Some sound");
}

// Method that can be overridden


public void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age);
}
}

// Child class (subclass)


public class Dog extends Animal {
private String breed;

public Dog(String name, int age, String breed) {

5
super(name, age); // Call parent constructor
this.breed = breed;
}

// Override parent method


@Override
public void makeSound() {
System.out.println(name + " says: Woof!");
}

// Override with additional functionality


@Override
public void displayInfo() {
super.displayInfo(); // Call parent method
System.out.println("Breed: " + breed);
}

// New method specific to Dog


public void fetch() {
System.out.println(name + " is fetching the ball");
}

// Getter for breed


public String getBreed() {
return breed;
}
}

// Usage
Animal animal = new Animal("Generic", 5);
Dog dog = new Dog("Buddy", 3, "Golden Retriever");

animal.makeSound(); // "Some sound"


dog.makeSound(); // "Buddy says: Woof!"
dog.fetch(); // "Buddy is fetching the ball"

Polymorphism
// Interface
public interface Drawable {
void draw();
double getArea();
}

// Abstract class
public abstract class Shape implements Drawable {

6
protected String color;

public Shape(String color) {


this.color = color;
}

public String getColor() {


return color;
}

// Abstract method (must be implemented by subclasses)


public abstract double getPerimeter();
}

// Concrete classes
public class Circle extends Shape {
private double radius;

public Circle(String color, double radius) {


super(color);
this.radius = radius;
}

@Override
public void draw() {
System.out.println("Drawing a " + color + " circle with radius " + radius);
}

@Override
public double getArea() {
return Math.PI * radius * radius;
}

@Override
public double getPerimeter() {
return 2 * Math.PI * radius;
}
}

public class Rectangle extends Shape {


private double width;
private double height;

public Rectangle(String color, double width, double height) {


super(color);
this.width = width;

7
this.height = height;
}

@Override
public void draw() {
System.out.println("Drawing a " + color + " rectangle " + width + "x" + height);
}

@Override
public double getArea() {
return width * height;
}

@Override
public double getPerimeter() {
return 2 * (width + height);
}
}

// Polymorphic usage
Shape[] shapes = {
new Circle("Red", 5.0),
new Rectangle("Blue", 4.0, 6.0),
new Circle("Green", 3.0)
};

for (Shape shape : shapes) {


shape.draw();
System.out.println("Area: " + shape.getArea());
System.out.println("Perimeter: " + shape.getPerimeter());
System.out.println();
}

Interfaces
// Basic interface
public interface Movable {
void move();
void stop();
}

// Interface with default method


public interface Playable {
void play();

default void pause() {

8
System.out.println("Paused");
}

default void stop() {


System.out.println("Stopped");
}
}

// Interface with static method


public interface MathOperations {
int add(int a, int b);
int subtract(int a, int b);

static int multiply(int a, int b) {


return a * b;
}
}

// Implementing multiple interfaces


public class Car implements Movable, Playable {
private String brand;
private boolean isRunning;

public Car(String brand) {


this.brand = brand;
this.isRunning = false;
}

@Override
public void move() {
if (isRunning) {
System.out.println(brand + " car is moving");
} else {
System.out.println("Start the car first");
}
}

@Override
public void stop() {
System.out.println(brand + " car stopped");
}

@Override
public void play() {
System.out.println("Playing music in " + brand + " car");
}

9
public void start() {
isRunning = true;
System.out.println(brand + " car started");
}

public void turnOff() {


isRunning = false;
System.out.println(brand + " car turned off");
}
}

Encapsulation
public class BankAccount {
// Private fields (data hiding)
private String accountNumber;
private double balance;
private String ownerName;
private static int accountCounter = 1000;

// Constructor
public BankAccount(String ownerName, double initialBalance) {
this.accountNumber = "ACC" + (++accountCounter);
this.ownerName = ownerName;
this.balance = initialBalance;
}

// Public getters
public String getAccountNumber() {
return accountNumber;
}

public double getBalance() {


return balance;
}

public String getOwnerName() {


return ownerName;
}

// Public methods with validation


public boolean deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposited: $" + amount);

10
return true;
} else {
System.out.println("Invalid deposit amount");
return false;
}
}

public boolean withdraw(double amount) {


if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("Withdrawn: $" + amount);
return true;
} else {
System.out.println("Invalid withdrawal amount or insufficient funds");
return false;
}
}

public void displayInfo() {


System.out.println("Account: " + accountNumber);
System.out.println("Owner: " + ownerName);
System.out.println("Balance: $" + balance);
}
}

Quick Reference
Class Components
• Fields: Instance variables and static variables
• Constructors: Initialize objects
• Methods: Instance methods and static methods
• Access Modifiers: public, protected, default, private
• Inheritance: extends keyword
• Interfaces: implements keyword

OOP Principles
• Encapsulation: Data hiding with private fields and public methods
• Inheritance: Code reuse through class hierarchy
• Polymorphism: Same interface, different implementations
• Abstraction: Hide complexity, show essential features

11
Best Practices
1. Use meaningful class and method names
2. Follow single responsibility principle
3. Use appropriate access modifiers
4. Override equals(), hashCode(), and toString()
5. Use composition over inheritance when possible
6. Keep classes focused and cohesive
7. Use interfaces for multiple inheritance
8. Implement proper encapsulation
9. Use static members sparingly
10. Document public APIs

12

You might also like