Class:
- A class is a blueprint or a template for creating objects.
- It contains variables and methods.
class Car {
String color; // Variable
void drive() { // method
System.out.println("Car is driving");
}
}
Object:
- An object is an instance of a class.
- It represents a real-world entity and has both state (variables) and (methods)
- Objects are created from classes using the new keyword in Java
Car myCar = new Car(); // object created
myCar.color = "Red";
myCar.drive();
Method:
- A method in Java is a block of code that performs a specific task.
- It defines the behavior of an object.
- Methods allow code reusability, improve readability.
1)With return type:
class Calculator {
int add(int a, int b) { // return type is int
return a + b; // must return an int value
}
}
2)Without return type:
class Car {
void drive() { // no return type
System.out.println("Car is driving...");
}
}
- If a method returns a value, specify the return type (e.g., int, String).
- If it does not return anything, use void.
Inheritance:
- one class can acquire the properties and behaviors of another class.
- The keyword extends is used to implement inheritance.
- It helps in code reusability and method overriding, making the program more organized.
class Animal {
void eat() {
System.out.println("Eating...");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Barking...");
}
}
public class Test {
public static void main(String[] args) {
Dog d = new Dog();
d.eat();
d.bark();
}
}
Polymorphism:
- Polymorphism in Java means one thing having many forms.
- Polymorphism allows the same method or object to perform different tasks depending on the situation.
There are two types:
1)compile-time polymorphism (method overloading)
2)Runtime polymorphism (method overriding).
1) Method Overloading (Compile-time):
- Same method name, but different parameters.
- Runs at compile time.
class Maths {
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}
public class Test {
public static void main(String[] args) {
Maths m = new Maths();
System.out.println(m.add(5, 3)); //calls 2nd one
System.out.println(m.add(5, 3, 2));//calls 3rd one
}
}
2)Method Overriding(Run time):
- When a child class inherits from a parent class, and both have the same method signature
- The child class method overrides the parent class method.
class Parent {
void display() {
System.out.println("This is parent class method");
}
}
class Child extends Parent {
void display() {
System.out.println("This is child class method");
}
}
public class Test {
public static void main(String[] args) {
Parent p = new Child(); // parent reference, child object
p.display(); // calls child method (overridden)
}
}
Top comments (0)