How to use constructors in Java? - java

//Vehicle.java
import java.util.Random;
class VehicleConstructor{
private int speed;
private int timeDriven;
private int run;
private int startSpeed; //Pradinis greitis
public VehicleConstructor() {
setSpeed();
System.out.println("Vehicle");
}
private void setSpeed(){
int minSpeed = 1;
int maxSpeed = 40;
Random random = new Random();
this.startSpeed = random.nextInt(maxSpeed - minSpeed + 1) + minSpeed;
}
protected int getSpeed(){
return startSpeed;
}
}
class Bicycle extends VehicleConstructor{
public void Bicycle(){
System.out.println(getSpeed());
}
}
public class Vehicle{
public static void main(String[] args){
Bicycle bicycle = new Bicycle();
}
}
I want to create object Bicycle which extends VehicleConstructor and call method getSpeed() from parent. The problem is that i get an error:
Error: Main method not found in class Bicycle, please define the main
method as: public static void main(String[] args)
As far as i know in Java constructors are with the same name as the class, so i have
public void Bicycle(){
System.out.println(getSpeed());
}
But error says that i need public static void main, and so the other classes also need to be with static, but i don't want this. Is it possible somehow create object without need of static method in it?

public void Bicycle(){ //This is a method
public Bicycle(){ //This is a constructor
Constructor's don't have any return type, not even void.

The error is self evident.. you dont have a main method, or for some reason, bicycle is defined as entry point when it should not be. After a second glance, looks like your Vehicle should be defined as the entry point, and its not.
p.s your class hierarchy is confusing.

create a separate class having main method to test (without this your program will not execute as it is the starting point) where you can create constructors of your classes

Your class works fine for me..What is the name of the file in which you have written code?File name should be equal to public class name..

I am guessing you are trying to run this class by itself. Java runtime needs that
public static void main(String[] args)
method when you try to run the class on its own. Try to create another Java class like Test.java that has main function and call the constructor inside it. Be sure to run Test.java otherwise you will keep getting the same error.

please , try to seperate the classes into seperates files, and name the files as the name of classes. then you add a public static void main(String[]arg) in the Bicycle class. then run it and you will see the results.

The problem is not at compile time, because even if you compile those files separately, they should compile fine. My guess is you are probably using an IDE (Netbeans or Eclipse) and you are not setting up Vehicle.java as the main class.

Related

Getting the name of class in inherited static method in Java

Say I want to solve a bunch of Project Euler problems in Java, and rather than give each problem class the boilerplate of its own main method, inherit it and have a "solve" method instead.
Is there a way of getting the problem class's name to print out along with the solution?
What I have:
abstract class Problem {
private static String problemName = ???
public static void main(String[] args) {
// If I could summon an instance of the sub-class then it would be easy
// Problem p = new ... what?
System.out.println(problemName + ": " + solve());
}
abstract static long solve();
// oops, you can't do abstract static in Java :(
}
then
public class Euler_001 extends Problem {
static long solve() {...}
}
The problem is that the various hacks to get the class name given in this answer return "Problem", not "Euler_001".
I guess I have to instantiate the problem class, but then how do I do that?
The static context does not help inheritance where the parent needs to call the child. Use instances with abstraction:
abstract class Problem {
public static void main(String[] args) throws Exception {
Problem problem;
//Now, depending on where the exact problem is specified:
//Class known at compile time
problem = new Euler_001();
//Class passed as parameter
problem = (Problem) Class.forName(args[0]).getConstructor().newInstance();
System.out.println(problem.getProblemName() + ": " + problem.solve());
}
abstract long solve();
abstract String getProblemName();
}
And the subclass will provide a normal implementation that overrides abstract methods:
class Euler_001 extends Problem {
#Override
long solve() {
return 0;
}
#Override
String getProblemName() {
return "????";
}
}
Depending on your configuration approach, you can create an instance of the concrete class based on the class name, inside the parent's main method.
This way, the Problem class can be called with:
java com.mypackage.Problem "com.mypackage.Euler_001"
Static variables and methods can not be overriden - they get replaced. So, as per my understanding we need to create instance of sub-class.
I checked -
Problem p = new Euler_001();
System.out.println(p.getClass().getSimpleName()); //prints Euler_001

Why make an object for Main class, for the methods to work?

I was facing an error before, but when I made an object in this class the and called for the method, it worked flawlessly. Any explanation? Do I always have to make an object to call for methods outside of the main method (but in the same class)?
here:
public class A{
public static void main(String[] args){
A myObj= new A();
System.out.println(myObj.lets(2));
}
public int lets(int x){
return x;
}
}
You need to understand static. It associates a method or field to the class itself (instead of a particular instance of a class). When the program starts executing the JVM doesn't instantiate an instance of A before calling main (because main is static and because there are no particular instances of A to use); this makes it a global and an entry point. To invoke lets you would need an A (as you found), or to make it static (and you could also limit its' visibility) in turn
private static int lets(int x) {
return x;
}
And then
System.out.println(lets(2));
is sufficient. We could also make it generic like
private static <T> T lets(T x) {
return x;
}
and then invoke it with any type (although the type must still override toString() for the result to be particularly useful when used with System.out.println).
There are a importance concept to consider an is static concept. In your example you have to create an instance of your class because the main method is static and it only "operate" with other statics methods or variable. Remember that when you instantiate a class you are creating a copy of that class an storing that copy in the instance variable, so as the copy (That was create inside of a static method in your case) is also static so it can access the method which is not static in that context.
In order to not create an instance and access to your method you need to make your lets method static(due to the explanation abode)
public static int lets(int x){
return x;
}
And in your main you don't need to instantiate the class to access to this method.
public static void main(String[] args){
System.out.println(lets(2));
}
Check this guide about static in java: https://www.baeldung.com/java-static
Hope this help!

Can't access functions in another class

****EDIT** For everyone saying call it like
FunctionTestTest.numberCheck(userNumber);
I have tried that numerous times before posting on here it didnt work.
People downvote a question that they cant even answer, great...
On another project Im working on I couldn't call functions from another class. Been trying to fix it all day. Decided to throw up a a few lines of code & try call a function from another class just to make sure i didn't have an unnoticed syntax error in my main project.
can anyone see what the problem is here?
returning this error:
cannot find the symbol
symbol: class FunctionTestTest
location: class FunctionTest
...
public class FunctionTest{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int userNumber = 0;
System.out.println("Please enter a number between 1 - 10");
userNumber = input.nextInt();
FunctionTestTest ft = new FunctionTestTest();
FunctionTestTest.numberCheck(userNumber);
}
}
and..
public class FunctionTestTest{
public static void main(String[] args){
}
public static void numberCheck(int num){
if (num == 1){
System.out.println("function works");
}
}
}
The error is caused because you are probably using class from another package. In this case you have to import it first before using.
If you are using any IDE there should be a hotkey to fixing your problem.
Also...
You don't need to create an object instance to access static methods of certain class. Simply use:
FunctionTestTest.numberCheck(userNumber);
It is not recommended, but you can call a static method on object instance like:
new FunctionTestTest().numberCheck(userNumber);
here you are calling other class constructor and is not present there:
FunctionTestTest ft = new FunctionTestTest(userNumber);
also check if FunctionTestTest class present is some other package then import it
ft.(userNumber);
Your method invocation is incorrect.
Your probably wanted ft.numberCheck(userNumber) or FunctionTestTest.numberCheck(userNumber). The latter is preferred as you are incoking a static member.
If is it a static method, you just call it as:
ClassName.methodName();
There is no need to instantiate an object to use a static method like what you did.
Example:
public class MyClass{
public static void myMethod(){
//do whatever..
}
}
public class OtherClass{
public static void main(String[] args){
MyClass.myMethod(); //invoke a static method from another class
}
}

Unable to access variables in different classes

package penny_pinch_v2;
public class Prizes {
public static String[] prizes = { "Puzzle", "Poster", "Ball", "Game", "Doll" };
}
===========Separate Class File============
package penny_pinch_v2;
public class RunPennyPinch {
public static void main(String[] args) {
System.out.print(prizes[1]);
}
}
I'm trying to access the array 'prizes' in a different class, but it keeps saying that 'prizes' cannot be resolved. If you could tell me how to fix this that would be great.
If you are referencing a static field in another class you will need to use the name of that class to reference the field, so basically you need to change your main to this:
public class RunPennyPinch {
public static void main(String[] args) {
System.out.print(Prizes.prizes[1]);
}
}
This is called a namespacing issue. Let's pretend you could do what you're trying to do. What if you make another class called Prizes2 and put another variable in it, also named prizes? How does RunPennyPinch know which prizes variable it should be using?
Perhaps you could solve this problem by saying, "only one prizes variable is allowed to exist in any program at one time". If this were a real limitation, you would quickly run out of meaningful names to give to variables.
The solution that Java came up with is namespacing: To give a variable a context it lives in. Two variables can have the same name, but as long as they have a different context, they won't clash. The price you pay is you have to tell the program which context you want to use when you're referring to a variable.
Here's how to fix the problem:
package penny_pinch_v2;
public class Prizes {
public static String[] prizes = { "Puzzle", "Poster", "Ball", "Game", "Doll" };
}
//===========Separate Class File============
package penny_pinch_v2;
public class RunPennyPinch {
public static void main(String[] args) {
System.out.print(Prizes.prizes[1]);
}
}
There's something else you should know: If you don't explicitly state a context, it defaults to using this as the context. As an unrelated example, these two methods do the same thing and both work:
package foo;
public class Bar {
public String baz = "Puzzle";
public void impliedThis() {
System.out.println(baz);
}
public void explicitThis() {
System.out.println(this.baz);
}
}
You have to prefix the variable with the class name as the variable is not within the RunPennyPinch class.
System.out.print(Prizes.prizes[1]);
You may also have to import the Prizes class, depending on your set-up.
The variable itself doesn't exist in that context. It's a static member of another class. So you need a reference to that class:
System.out.print(Prizes.prizes[1]);
The main advantage of static is that you dont have to create an object to access that variable. You just have to call that variable by Classname.variablename (Classname is the name of class in which that variable was present)
System.out.print(Prizes.prizes[1]);

Multiple main() methods in java

I was wondering what the effect of creating extra main methods would do to your code.
For example,
public class TestClass {
public static void main (String[] args){
TestClass foo = new TestClass();
}
}
After the program initially starts up, foo will be created and it would have another public main method inside it. Will that cause any errors?
It will cause no errors. Just because you initialize an object, doesn't mean the main method gets executed. Java will only initially call the main method of the class passed to it, like
>java TestClass
However, doing something like:
public class TestClass
{
public static void main (String[] args)
{
TestClass foo = new TestClass();
foo.main(args);
}
}
Or
public class TestClass
{
public TestClass()
{
//This gets executed when you create an instance of TestClass
main(null);
}
public static void main (String[] args)
{
TestClass foo = new TestClass();
}
}
That would cause a StackOverflowError, because you are explicitly calling TestClass's main method, which will then call the main method again, and again, and again, and....
When in doubt, just test it out :-)
The main method is static, which means it belongs to the class rather than the object. So the object won't have another main method inside it at all.
You could call the main method on instances of the object, but if you do that it's literally just another way of calling TestClass.main() (and it's frowned upon by many, including me, to call a static method on an instance of an object anyway.)
If you're referring to multiple main methods in the same program, then this isn't a problem either. The main class is simply specified and its main method is executed to start the program (in the case of a jar file this is the main-class attribute in the manifest file.)
It won't have an additional main-method, as main is static. So it's once per class.
If you have multiple main-methods in your project, you will specify which one to launch when starting your application.
This is perfectly fine. Having multiple main methods doesn't cause any problems. When you first start a Java program, execution begins in some function called main in a class specified by the user or by the .jar file. Once the program has started running, all the other functions called main are essentially ignored or treated like other functions.
After searching for a Java Class with multiple main() methods or in plain words, overloaded main() methods, I came up with an example of my own. Please have a look
public class MultipleMain{
public static void main(String args[]){
main(1);
main('c');
main("MyString");
}
public static void main(int i){
System.out.println("Inside Overloaded main()");
}
public static void main(char i){
System.out.println("Inside Overloaded main()");
}
public static void main(String str){
System.out.println("Inside Overloaded main()");
}
}
I tested this Java Code on JDK 1.7 and works like a charm !
You need "public static void main(String args[])" to start with and then you can call overloaded main methods inside this main and it should work for sure.
Any comments and suggestion are highly appreciated. I am just a novice Java Developer willing to develop my Java skills.
Thanks,
PK
No, you can have any number of main-methods in a project. Since you specify which one you want to use when you launch the program it doesn't cause any conflicts.
You can have only one main method in one class, But you can call one main method to the another explicitly
class Expmain
{
public static void main(String[] ar)
{
System.out.println("main 1");
}
}
class Expmain1
{
public static void main(String[] ar)
{
System.out.println("main 2");
Expmain.main(ar);
}
}
when you run your Java class it will always look for the signature public static void main(String args[]) in the class. So suppose if you invoking by command line argument, it will look for the method Signature in the class and will not invoke other until if u explicitly inoke it by its class name.
class MainMethod1{
public static void main(String[] ags){
System.out.println("Hi main 1");
testig2 y = new testig2();
//in this case MainMethod1 is invoked/.......
// String[] a = new String[10];
// testig2.main(a);
}
}
class MainMethod2{
public static void main(String[] ags){
System.out.println("Hi main 2");
}
}
But when you try the same from eclipse it will ask for which class to compile. Means MainMethod1 or Mainmethod2. So if te class has the exact signature they can be used as individual entry point to start the application.
Coming to your question, If you remove the signature as u did above by changing the argument if main method. It will act as a normal method.
It is all about the execution engine of JVM. Remember, you write >java com.abc.MainClass on cmd prompt.
It explains everything. If main method is not found here it throws a run time Error:Main Method Not Found in class MainClass.
Now if main method is found here, it acts as the first point when Program Counters have to map and start executing the instructions. Referred classes are loaded then, referred methods may be called using the instances created inside. So, main is class specific though one class can have only one main method.
Please note, main method's signature never changes. You can have two overloaded main methods in same class, like
public static void main(String[] args) {}
public static void main() {} //overloaded in same class.
During Static binding, the original main is resolved and identified by execution engine.
Another interesting point to consider is a case where you have two different classes in of java file.
For example, you have Java file with two classes:
public class FirstClassMultiply {
public static void main (String args[]){
System.out.println("Using FirstClassMultiply");
FirstClassMultiply mult = new FirstClassMultiply();
System.out.println("Multiple is :" + mult.multiply(2, 4));
}
public static void main (int i){
System.out.println("Using FirstClassMultiply with integer argument");
FirstClassMultiply mult = new FirstClassMultiply();
System.out.println("Multiply is :" + mult.multiply(2, 5));
}
int multiply(int a, int b) {
return (a * b);
}
}
class SecondClass {
public static void main(String args[]) {
System.out.println("Using SecondClass");
FirstClassMultiply mult = new FirstClassMultiply();
System.out.println("Multiply is :" + mult.multiply(2, 3));
FirstClassMultiply.main(null);
FirstClassMultiply.main(1);
}
}
Compiling it with javac FirstClassMultiply.java will generate two .class files, first one is FirstClassMultiply.class and second one is SecondClass.class
And in order to run it you will need to do it for the generated .class files: java FirstClassMultiply and java SecondClass, not the original filename file.
Please note a couple of additional points:
You will be able to run SecondClass.class although it's class wasn't public in the original file!
FirstClassMultiply overloading of the main method
of is totally fine, but, the only entry point to your prog
will be the main method with String args[] argument.

Categories