why the main method is printing nothing in the sub class? - java

"mysecondclass" which is a sub class of the super class "myfirstclass"
should inherit all the properties of the super class "myfirstclass"
and it's expected to output the value of x but instead it prints nothing
package myfirstproject;
public class myfirstclass {
protected int x = 10;
//getter
public void getX() {
System.out.println(x);
}
public static void main(String[] args) {
/* it asked me to define this main method here although it's useless in this situation
*/
}
}
class mysecondclass extends myfirstclass {
public static void main(String[] args) {
mysecondclass mysecondobject = new mysecondclass();
mysecondobject.getX(); //prints nothing
}
}
i am really newbie in java and i am actually still learning it's basics
also i do not know why it always asks me to add the main method in the super class although i have already declared one in the sub class (i heard one main method is enough for one java file)
any help is really appreciated , thanks in advance

You are not understanding the function
public static void main(String[] args)
In Java Docs :
The public static void keywords mean the Java 1 virtual machine (JVM)
interpreter can call the program's main method to start the program
(public) without creating an instance of the class (static), and the
program does not return data to the Java VM interpreter (void) when it
ends.
You have two
public static void main(String[] args)
In two different classes! You are running or compiling the one that uses myfirstclass So for this type of example or test is a good practice to have only one Java class Main
public class Main {
public static void main(String[] args) {
// Call Your classes
}
}
Be more clean and organized in your code!
And one other thing. For running by Command Line use this type of commands
java MyApp arg1 arg2
When in doubt always read the Docs!

You have 2 ways to make your code running as you wish
1) create 2 java file. one is myfirstclass.java the second is mysecondclass.java. each hold their main class. Thus you can kick off any main method as you wish.
2) just keep these 2 class in the same java file. then when you running it, it will only run the main method in default in the public class.

Just change the public keyword to the second class. If you are using an online compiler, they usually look for the main method inside the public class.
package myfirstproject;
class myfirstclass {
protected int x = 10;
//getter
public void getX() {
System.out.println(x);
}
}
public class mysecondclass extends myfirstclass {
public static void main(String[] args) {
mysecondclass mysecondobject = new mysecondclass();
mysecondobject.getX(); //printx X
}
}

Related

How do you transfer a variable defined in the main method of one class to another?

I have seen this done in many programs but I cant seem to follow the programming logic.
Lets say you have a simple class, ClassB. And in ClassB's main method you define an integer variable:
public class B {
public static void main(String[] args) {
int stuff = 333;
}
}
How can you transfer the variable to a different class, say ClassA, to be used.
public class A {
public static void main(String[] args) {
System.out.println(stuff);
}
}
Can someone please explain this to me in simple terms. I've been trying to learn this for 2 hours and cant wrap my head around it.
public static void main(String[] args) is meant to be used as a starting point for a Java program. Probably it's better to rename one of your methods to something else.
The problem you are seeing, is that the scope of the variable int stuff is limited to the main() method of class B, because it is declared within the body of the main() method. In order to make it visible, you need to declare it as a public field (which can be static in your case).
I propose you change your program like follows:
public class A {
public static int stuff;
public static void initStaticMembers() {
stuff = 333;
}
}
public class B {
public static void main(String[] args) {
A.initStaticMembers();
System.out.println(A.stuff);
}
}
I renamed the main() method of A to initStaticMembers() and dropped the method parameters, since they are not needed in our case. In order to use the field A.stuff in B, the method A.initStaticMembers() needs to be called first.
Of course there are ways to improve this program, but I think you should learn Java one step at a time.
You shouldn't have 2 main methods. Only one class should (typically):
ClassA.java
public class A {
public static void main(String[] args) {
ClassB b = new ClassB();
System.out.println(b.stuff);
}
}
ClassB.java
public class B {
public int stuff = 333; // member variable
}
You instantiate the second class in the first one, then you're granted access to its public member variables.

what does the error statement define in the case of main method Overloading

public class Sample{
public static void main(String args[]){
System.out.println("/n Say hi 2 me");
}
public class Hello{
public static void main(String args[]){
System.out.println("/n Hello!");
}
}
}
I have run this code using Command Prompt but I was able to notice that modifier 'static' is used for only constant variable Declarations
why?????
please help me out in understanding this???
public static void main(String[] args)
main method with single String[] (or) String... as param will be considered as entry point for the program.
So we cant have two completely same main methods in one java class
you can have other method named main but it should have different parameters(overloading of method)
static can be used with variables as well as methods but can't be used for a class
static variables are initialized before the object creation when the class is loaded and static
methods can be called before object creation as well

Why doesn't the class containing main have to be public?

I declared the following class
class A { //not public
public static void main(String args[]) {
System.out.println("done");
}
When I compile and run it, it runs fine and prints the output "done". Same behavior even when I declare it as being in a "package a;"
However, if JVM spec mandates that main method should be public since "it can't see main otherwise", shouldn't it apply to the class as well?
If the JVM "can't see" A.main() when it is not declared public, how is it able to see the class A itself.
Is there any explanation for this other than "because the specification says so"?
The JVM has access to every class in the application all the time because one of its responsibilities is enforcing visibility rules. Therefore, one can draw the conclusion that it can ignore visibility rules if need be (e.g. when the user starts the application, the JVM has to find the entry point, which is main()).
In other words, the JVM is not a class accessing this function, so visibility doesn't apply. It is basically the overseer, managing the application from execution to termination.
For reference, see Execution.
When you declare a class private, you're not making it "invisible", and the same goes for your methods. Declaring a method private simply means it's not callable from outside your class. A static public method of a private class is publicly callable.
The reason the JVM can see a non-public class is because it controls visibility, meaning it sees everything and decides what can see/call/access what.
The use of public on a class is different than on a method, but the concept is the same.
On a method, the public keyword means the method can be used outside the class. An example would be:
class A {
public static void do() {
// Do something
}
}
class B {
public static void main(String[] args) {
A.do(); // This works because do() is public and static
}
}
The same concept applies to classes, but in a different way.
Using public on a class means that it can be used outside the current .java file (it will have its own .class file).
Here's an example:
//C.java
class C {
static void do() {
// Do something
}
public static void run() {
A.do(); // Works because A.do() is public and static
B.do(); // Does not work because B is not a public class
}
}
//A.java
public class A {
public static void main(String[] args) {
B.do(); // Works because B is in the same file
do(); // Duh...
}
public static void do() {
// Do something
}
}
class B {
static void do() {
// Do something
}
}

Getting strange java.lang.NoSuchMethodError error

I have an interface called Namable
public interface Namable { public String getName(); public void setName(String name); };
Several classes will implement this.
When I make code like this:
Namable foo = new X(); foo.getName();
(X is an implementing class)
I get the error:
java.lang.NoSuchMethodError: Namable.getName()Ljava/lang/String;
This is very strange to me and I'm wondering why this is happening, any thoughts?
Compilable example:
Namable class:
public interface Namable
{
public String getName();
}
Extending class X:
public class X extends java.util.ArrayList implements Namable
{
private String name;
public X()
{
this.name = "bar";
}
public String getName()
{
return name;
}
}
Testing class:
public class Test
{
public static void main()
{
Namable foo = new X();
foo.getName();
}
}
After running this, I get the same error. I am using BlueJ
I have run an example with the classes you have given here and it works as expected once the main method is changed to:
public static void main(String[] args)
However, as you are using BlueJ this may not be a problem (I remember BlueJ using a special mechanism to run classes).
Do you have another class Nameable in your classpath? Check the package import and make sure it is the interface you have defined. It appears the error is with your environment and not with the code.
You need to call
foo.getName()
not
X.getName()
You are trying to call a class (static) method that doesn't exist.
And it should be Namable foo = new X(); - your example code shouldn't even compile as shown.
Can you provide a SSCCE ?
Updated following corrections and SSCCE: Just a wild guess now, but does BlueJ define a Namable already, or do you have a Namable in another package that might be imported instead? What happens if you rename Namable to Namable2 throughout, in the example above?
As stated by DNA your post would be better with a SSCCE
My guess would be that maybe you could have missed a "static" keyword in main function
public static void main(String args[])
not
public void main(String args[])
Could be something a classpath problem too... Or a file name and class mismatch. Or something else.
When I ran your code snippet, the error shown is
Error: Main method not found in class Test, please define the main
method as: public static void main(String[] args)
Change your main method to
public static void main(String[] args)
I am not getting
java.lang.NoSuchMethodError: Namable.getName()Ljava/lang/String;
with your given code snippet.

Main method in a static inner class.?

I've learnt that the only public class in a Java file must also have the main method. However, below you can see the main method inside an inner class instead?
What is the rule with regard to the main method definition in a source file?
public class TestBed {
public TestBed() {
System.out.println("Test bed c'tor");
}
#SuppressWarnings("unused")
private static class Tester {
public static void main(String[] args) {
TestBed tb = new TestBed();
tb.f();
}
}
void f() {
System.out.println("TestBed::f()");
}
}
If you want to start a class with java (the Java launcher: java test.MyClass) then this class must have a main method with the well known signature.
You can have a main method with the same signature anywhere you want. But don't expect that the launcher will find it.
P.S. The name of the language is Java, not JAVA.
There is a minor detail:
You may do this:
package test;
public class Test {
/**
* #param args the command line arguments
*/
static public class A {
public static void main(String[] args) {
System.err.println("hi");
}
}
}
java test.Test$A
but this is non standard ...
Any class that can have a static method can have a public static void main(String[] args).
This includes:
top-level classes (whether public or not), e.g.
public class Foo {
public static void main(String[] args) {
System.out.println("Hello");
}
}
and inner static classes (whether public or not) (like your example).
It does not include:
anonymous classes
inner non-static classes
So both of these are illegal:
public class Foo {
private Object bar = new Object() {
public static void main(String[] args) {
System.out.println("Hello");
}
};
}
public class Foo {
private class Bar {
public static void main(String[] args) {
System.out.println("Hello");
}
};
}
Every Java application must have a main method. It’s the starting point for the execution of the code in the application. Its method signature is:
public static void main(String[] args)
A static inner class is a class that is defined inside of a different class's definition and marked as being static.
For example, if the outer class is named TestBed, then an inner class of TestBed, which is named Tester, would be compiled into TestBed$Tester.class. The separation of .class files means that you can keep the supplemental, nested code tightly coupled to the primary, outer class.
They are in the same source file, and the inner class is actually inside the outer class. All that and you don't have to pay any sort of deployment or run time cost.
By using static inner classes, you can add additional support functionality to your systems for capabilities such as testing, while incurring no penalties in normal, production deployment.
To execute the main() method of that TestBed.Tester class,
% java TestBed$Tester
This is interesting as the code will compile and run in Eclipse, but will just compile from using commmand line. When you run from eclipse it will find the static main method from within the inner class and run it.
But when running java TestBed from the command line you will get error - Exception in thread "main" java.lang.NoSuchMethodError: main which is a valid error as you have not defined your main method in main class.
Why would you want to define your main method in an inner class? Your main method should be defined in public class, this is not a rule but common practice.
In below code I've moved the main method into outer class which works both in Eclipse & command line :
public class TestBed {
public TestBed() {
System.out.println("Test bed c'tor");
}
#SuppressWarnings("unused")
private static class Tester {
}
public static void main(String[] args) {
TestBed tb = new TestBed();
tb.f();
}
void f() {
System.out.println("TestBed::f()");
}
}

Categories

Resources