Assignment No1 (JAVA)
Assignment No1 (JAVA)
1 Submission Date:
1. Write a Java program to illustrate the concept of class with method overloading.
Ans: -
public class Calculator {
// Method to add two integers
public int add(int a, int b) {
return a + b;
}
Ans: -
public class StaticDemo {
// Static variable
static int staticVar = 10;
// Instance variable
int instanceVar;
// Static method
static void staticMethod() {
System.out.println("Inside static method.");
// Can access static variables
System.out.println("Static variable: " + staticVar);
// Cannot access instance variables directly
// System.out.println("Instance variable: " + instanceVar); // This
would cause an error
}
// Instance method
void instanceMethod() {
System.out.println("Inside instance method.");
// Can access both static and instance variables
System.out.println("Static variable: " + staticVar);
System.out.println("Instance variable: " + instanceVar);
}
// Static block
static {
System.out.println("Inside static block.");
staticVar = 20; // Can initialize static variables
}
Ans: -
Ans: -
// Base class
class Animal {
void makeSound() {
System.out.println("Some generic animal sound");
}
}
// Derived class 1
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Bark");
}
}
// Derived class 2
class Cat extends Animal {
@Override
void makeSound() {
System.out.println("Meow");
}
}
// No-argument constructor
public Student() {
this.name = "Unknown";
this.age = 0;
}
// Parameterized constructor
public Student(String name, int age) {
this.name = name;
this.age = age;
}
// Copy constructor
public Student(Student student) {
this.name = student.name;
this.age = student.age;
}