0% found this document useful (0 votes)
6 views2 pages

Part2 Java Programs-1

Uploaded by

Maya Joshi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views2 pages

Part2 Java Programs-1

Uploaded by

Maya Joshi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

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) {
System.out.println("Square of 5 = " + MathHelper.square(5));
}
}

2(b) Constructor chaining


class Chain {
Chain() {
this(10); // calling parameterized constructor
System.out.println("Default Constructor");
}

Chain(int x) {
System.out.println("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 {
System.out.println("Static block executed");
}

// init block
{
System.out.println("Initialization block executed");
}

// constructor
BlocksDemo() {
System.out.println("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() {
System.out.println("Class A method");
}
}

class B extends A { // Single


void showB() {
System.out.println("Class B method");
}
}

// Multilevel Inheritance
class C extends B {
void showC() {
System.out.println("Class C method (multilevel)");
}
}

// Hierarchical Inheritance
class D extends A {
void showD() {
System.out.println("Class D method (hierarchical)");
}
}

public class InheritanceDemo {


public static void main(String[] args) {
C obj1 = new C();
obj1.showA();
obj1.showB();
obj1.showC();

D obj2 = new D();


obj2.showA();
obj2.showD();
}
}

2(e) Method overloading and overriding


// Overloading
class OverloadDemo {
void display(int x) {
System.out.println("Integer: " + x);
}
void display(String s) {
System.out.println("String: " + s);
}
}

// Overriding
class Parent {
void greet() {
System.out.println("Hello from Parent");
}
}

class Child extends Parent {


void greet() {
System.out.println("Hello from Child");
}
}

public class OverloadOverrideDemo {


public static void main(String[] args) {
OverloadDemo obj1 = new OverloadDemo();
obj1.display(10);
obj1.display("Java");

Parent p = new Parent();


Parent c = new Child();
p.greet();
c.greet();
}
}

You might also like