Java for Beginners – Functions & Object-Oriented Basics
1. What are Functions (Methods) in Java?
A function (in Java we call it a method) is a block of code that performs a specific task.
Instead of repeating code, you write it once inside a method and call it whenever you need it.
Example:
2. Why Use Methods?
✅ Reusability – Write once, use many times
✅ Cleaner code – Easier to read & maintain
✅ Better structure – Breaks big programs into smaller parts
3. Syntax of a Method
Example:
4. Calling a Method
5. Methods with Parameters and Return Values
6. Method Overloading
Two or more methods can have the same name but different parameter lists.
7. Introduction to Object-Oriented Programming (OOP)
Java is an object-oriented language, meaning everything revolves around classes and objects.
Key OOP Concepts:
-
Class → Blueprint or template for creating objects
-
Object → Instance of a class
-
Attributes → Variables inside a class (properties of the object)
-
Methods → Actions/behaviors inside a class
8. Creating a Class and Object
Output:
9. Constructors in Java
A constructor is a special method that runs automatically when an object is created.
10. Mini Practice Exercises
Task 1: Create a class Book
with attributes title and author, and a method displayDetails()
. Create objects for two books and display their details.
Task 2: Write a method isEven(int number)
that returns true
if the number is even, otherwise false
.
Task 3: Create a Calculator
class with overloaded methods for addition (int, double).
11. What’s Next?
In Blog 5, we’ll dive deeper into OOP concepts:
-
Access Modifiers
-
Inheritance
-
Method Overriding
-
Polymorphism
-
Encapsulation
💡 Tip: Think of a class like a "blueprint" and an object like the "real thing" built from that blueprint. Practice by modeling real-world things as Java classes.
Comments
Post a Comment