2

Context: Two classes from different packages (Second class in second package inherits class in first package) are connected through inheritance and made a method call to subclass from parent class.

What I did:

Written two classes in two different notepad files and trying executing one after other but was not possible for me to execute and showing error messages and my classes are as follows:

package first;

import second.Sample1;

public class Sample {

public static void main(String a[])
{
    Sample1 s=new Sample1();
    s.dis(1);
}


package second;

import first.Sample;

public class Sample1 extends Sample{
public void dis(int i)
{
System.out.println(i);
}
}

In Eclipse, it is giving output as 1 but in what order I should execute these codes using notepads files. Observed that compiling these classes in any order giving error messages.

Thanks much. :)

Vishwak
  • 158
  • 9

1 Answers1

1

You created a cyclic package dependency, which is not a good idea.

Your base class Sample doesn't have to know anything about its sub-classes, and when it does, it is usually a sign of bad design.

Just move the main method to Sample1, and Sample class won't have to import second.Sample1.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • And then delete `Sample`? The main problem here is that this isn't really an example of inheritance in any meaningful way. – Boris the Spider Apr 03 '16 at 06:46
  • @BoristheSpider I agree that as posted in the question, `Sample1` doesn't inherit any state or behavior from `Sample`, but I gave a general answer for cases in which the inheritance does make sense. – Eran Apr 03 '16 at 06:50
  • I can make Sample1 to inherit any state/behavior from Sample but is not my concern. Just to know, how to compile them? – Vishwak Apr 03 '16 at 06:55
  • @Vishwak Once you break the bad dependency, you can compile `Sample` first and then compile `Sample1`. – Eran Apr 03 '16 at 07:03
  • `C:\Users\PE>javac -d . Sample.java Sample1.java` `C:\Users\PE>java first.Sample` `1` Got my Answer. I got this problem in middle of my development and I will try avoid this dependency Much Thanks both. – Vishwak Apr 03 '16 at 07:13