0

Why can't I write like this? what's wrong in this? We can extend JFrame and can write it like that then why is that not possible in this case?

import java.util.Scanner;

class mainClass extends Scanner {
    private int number;
    
    
    mainClass() {
        super(System.in);
        System.out.print("Enter your number");
        number = nextInt();
        System.out.println("This is your number "+number);
    }
}

1 Answers1

1

Okay, I would suggest you to have a look at a simple java program reading Input from Console (System.in) Example. This way you can also get used to the Java Code Conventions.

Your code won't work, because looking at Scanner Class in JavaDoc, you will find the class is final, thus you cannot inherit from it. Also, this class alone will not work, because it does not have a main-method, which is called when you start the program.

CodingTil
  • 447
  • 2
  • 16
  • Why do JFrame classes doesn't have this - "final" concept? – agarsom par Jun 20 '20 at 10:58
  • Besides this post [https://stackoverflow.com/questions/218744/good-reasons-to-prohibit-inheritance-in-java] I personally can't give you a good explanation. Some classes are designed not to be changed. Perhaps classes that use System Resources should behave on all platforms equally, inherited classes could overwrite the functionality and change the behaviour. – CodingTil Jun 20 '20 at 11:04