Ramesh Kumar Chikoti
Ramesh Kumar Chikoti

Reputation: 356

How to make my class inherits the methods of other classes

I am beginner to core java. We know that multiple inheritance is not possible with classes, but my question is
In a business requirement there are two classes C1 and C2 already defined and given to us. Now C1 has method m1() and C2 has method m2(). Now my class is C3. How to access the methods of m1 and m2 defined in classes C1 and C2 in my class C3,

C3 c3=new C3();
c3.m1();
c3.m2();

By creating the instance of my class I should able to access the methods in the classes given to me
Note:: Code for the classes C1 and C2 should not be changed and I should not create the objects of C1 and C2, by creating the object of C3 I should be able to access the methods.

Can any please help me for solving this?

Upvotes: 0

Views: 69

Answers (2)

Mehak Batra
Mehak Batra

Reputation: 59

If you want multiple inheritance in your program u can use interface . But if you don't want to change your C1 and C2 Class so make C1 class as inner class of Interface. C1 class and its method should be static.

interface A
{
    static class C1
{
    static public void m1()
    {
        System.out.print("i am m1");
    }

}
}
class C2
{
    public void m2()
    {
        System.out.print("i am m2");
    }

}
public class C3 extends C2 implements A {
    public static void main(String args[])
    {
        C3 ob= new C3();
        A.C1.m1();
        ob.m2();
    }

}

Output: i am m1 i am m2

You can also use multi-level inheritance

class C1 
{
     public void m1()
    {
        System.out.print("i am m1");
    }

}

class C2 extends C1
{
    public void m2()
    {
        System.out.print("i am m2");
    }

}
public class C3 extends C2  {

    public static void main(String args[])
    {
        C3 ob= new C3();
        ob.m1();
        ob.m2();
    }

}

Output: i am m1 i am m2

Upvotes: 1

Michael
Michael

Reputation: 44090

Code for the classes C1 and C2 should not be changed and I should not create the objects of C1 and C2, by creating the object of C3 I should be able to access the methods.

Unless C2 extends C1 (or vice versa), this is not possible. You either need an instance of each (composition) or an inheritance hierarchy.

Upvotes: 2

Related Questions