For Mid Tern (Viva)
For Mid Tern (Viva)
class Car {
String brand;
int speed;
void display() {
System.out.println("Brand: " + brand + ",
Speed: " + speed); }
}
What is an Object?
• An object is an instance of a class.
• It has state (attributes) and behavior (methods).
• Objects occupy memory and interact with each other.
• Example of object creation in Java:
class Person {
String name;
int age;
Person(String n, int a) {
// Constructor
name = n;
age = a;
}
void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
Constructor Example
class OverloadExample {
void display(int a) {
System.out.println("Integer: " + a);
}
void display(double a) {
System.out.println("Double: " + a);
}
}
Method Overloading
Method Overloading in Java
• Same method name, different parameter lists.
• Achieved by changing:
• Number of parameters
• Data type of parameters
• Order of parameters
Method Overloading
Example:
class MathOperations {
int sum(int a, int b) {
return a + b;
}
Person(String n) {
name = n;
}
Person(String n, int a) {
name = n;
age = a;
}
}
Importing Header Files in Java
Importing Header Files
• Java does not use traditional "header files" like C++.
• Instead, Java uses import statements to include predefined classes from
packages.
Example:
import java.util.Scanner; // Importing Scanner class
// Parent class
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
• interface Showable {
• void show();
• }