Part 2 - Java Programs
2(a) Demonstrate static import
class MathHelper {
static int square(int n) {
return n * n;
}
}
public class StaticImportDemo {
public static void main(String[] args) {
[Link]("Square of 5 = " + [Link](5));
}
}
2(b) Constructor chaining
class Chain {
Chain() {
this(10); // calling parameterized constructor
[Link]("Default Constructor");
}
Chain(int x) {
[Link]("Parameterized Constructor with value: " + x);
}
}
public class ConstructorChaining {
public static void main(String[] args) {
Chain obj = new Chain();
}
}
2(c) Difference between constructor, static block, init block
public class BlocksDemo {
// static block
static {
[Link]("Static block executed");
}
// init block
{
[Link]("Initialization block executed");
}
// constructor
BlocksDemo() {
[Link]("Constructor executed");
}
public static void main(String[] args) {
BlocksDemo obj1 = new BlocksDemo();
BlocksDemo obj2 = new BlocksDemo();
}
}
2(d) Demonstrate all types of inheritance
// Single Inheritance
class A {
void showA() {
[Link]("Class A method");
}
}
class B extends A { // Single
void showB() {
[Link]("Class B method");
}
}
// Multilevel Inheritance
class C extends B {
void showC() {
[Link]("Class C method (multilevel)");
}
}
// Hierarchical Inheritance
class D extends A {
void showD() {
[Link]("Class D method (hierarchical)");
}
}
public class InheritanceDemo {
public static void main(String[] args) {
C obj1 = new C();
[Link]();
[Link]();
[Link]();
D obj2 = new D();
[Link]();
[Link]();
}
}
2(e) Method overloading and overriding
// Overloading
class OverloadDemo {
void display(int x) {
[Link]("Integer: " + x);
}
void display(String s) {
[Link]("String: " + s);
}
}
// Overriding
class Parent {
void greet() {
[Link]("Hello from Parent");
}
}
class Child extends Parent {
void greet() {
[Link]("Hello from Child");
}
}
public class OverloadOverrideDemo {
public static void main(String[] args) {
OverloadDemo obj1 = new OverloadDemo();
[Link](10);
[Link]("Java");
Parent p = new Parent();
Parent c = new Child();
[Link]();
[Link]();
}
}