Assignment-2 Answers
1. Define a Class in Java.
A class in Java is a blueprint from which individual objects are created. It defines the properties
(fields) and behaviors (methods) of the objects.
Example:
class Car {
String color;
int speed;
void drive() {
System.out.println("Car is driving");
2. Instance variable and method declaration.
Instance variables are defined inside the class but outside any method. Methods define behaviors.
Example:
class Student {
String name;
void display() {
System.out.println("Name: " + name);
3. Creating an object in Java.
Objects are created using the new keyword.
Example:
class Bike {
void run() {
System.out.println("Bike is running");
public static void main(String[] args) {
Bike b = new Bike();
b.run();
4. Program to demonstrate class and object.
class Person {
String name;
int age;
void display() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
public class Main {
public static void main(String[] args) {
Person p1 = new Person();
p1.name = "Alice";
p1.age = 22;
p1.display();
5. Constructor explanation.
A constructor initializes an object.
Example:
class Student {
String name;
Student(String n) {
name = n;
void display() {
System.out.println("Name: " + name);
public static void main(String[] args) {
Student s = new Student("John");
s.display();
6. Method overloading.
Method overloading allows multiple methods with same name but different parameters.
Example:
class Add {
int sum(int a, int b) {
return a + b;
double sum(double a, double b) {
return a + b;
}
7. Constructor overloading.
Multiple constructors with different parameters.
Example:
class Employee {
String name;
int age;
Employee() {
name = "Unknown";
age = 0;
Employee(String n, int a) {
name = n;
age = a;
8. Access specifiers.
Access specifiers define visibility: public, private, protected, default.
Example:
class Sample {
public int a = 10;
private int b = 20;
void display() {
System.out.println("a = " + a);
System.out.println("b = " + b);
}
9. Static keyword.
Static is used for memory efficiency.
Example:
class Counter {
static int count = 0;
Counter() {
count++;
System.out.println(count);
10. Static blocks.
Used to initialize static data. Runs once.
Example:
class Test {
static int x;
static {
x = 10;
System.out.println("Static block initialized");