-1

In java when we inherit a public superclass then why we can't make the subclass public.

public class Parent {
    int value;
    public void print(){
        System.out.println("Hello Parent!");
    }

    public static void main(String[] args) {
        Parent t = new Child();

    }
}
public class Child extends Parent{ // error here
    int val;
}

// showing error if I use public, private or protected with Child class.

ADITYA RAJ
  • 123
  • 1
  • 2
  • 8

1 Answers1

0

Based on your question, it looks like you are defining both classes in same file.

When you are defining multiple classes in same file , then only one class will be public & you save your file with that class name (e.g. Parent.java in your case.).

If you want to define your Child class as public, then it is totally allowed, but create new file & define Child class there & save it with Child.java.

Alternatively, you can use Child & Parent classes within same file but remove public access modifier from Child so that compiler won't complain.

Ashish Patil
  • 4,428
  • 1
  • 15
  • 36