Why do I need a class here? - java

class Myclass{
int x;
Myclass(int i){
x = i;
}
}
class UseMyclass { //Why do I need another class?
public static void main (String args[]){
Myclass y = new Myclass(10);
System.out.println(y.x);
}
}
Why can't I run main() out of Myclass?
From the book it says I would be running the UseMyclass so I guess that would be my file name. Why couldn't I just use the Myclass though as the file name and run main() in there?
I'm new to programming so I'm just trying to figure stuff out.

You don't actually need another class. If you just put the main method into the class, it will work. For example, this code will work just fine:
class Myclass{
int x;
Myclass(int i){
x = i;
}
public static void main (String args[]){
Myclass y = new Myclass(10);
System.out.println(y.x);
}
}
However, separating the main class is a good idea when you are dealing with large programs with many classes. Then, you can sneak unit tests into main methods in other classes.

Related

A class with no modifier (default) cannot access a subclass declared as public? Java

I was just doing practice on Hackerrank since I'm still pretty new to Java (I'm only experienced with C and C++, with minimal Python/Matlab/C#). Basically we only had to write the "Checker class" below from scratch. However, I noticed that when I add public to the Checker class it results in runtime error. Does anyone know why? I couldn't find any answers on this online.
Also, yes, I know access modifiers restrictions on how much they can have access to the scope of classes, but it does not make sense to me on how a default class cannot access a public class's method. I'm assuming it is perhaps I'm implementing a parent class that's causing the problem? Here is the RE message I receive on Hackerrank:
Error: Main method not found in class Checker, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
If interested, link to the practice problem for reference: https://www.hackerrank.com/challenges/java-comparator/problem
import java.util.*;
// Write your Checker class here
class Checker implements Comparator<Player>{ //If I add "public" in front I get RE
#Override
public int compare(Player A, Player B){
if(A.score == B.score)
return A.name.compareTo(B.name);
else
return B.score - A.score;
// return A.compareTo(B);
}
}
class Player{
String name;
int score;
Player(String name, int score){
this.name = name;
this.score = score;
}
}
class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
Player[] player = new Player[n];
Checker checker = new Checker();
for(int i = 0; i < n; i++){
player[i] = new Player(scan.next(), scan.nextInt());
}
scan.close();
Arrays.sort(player, checker);
for(int i = 0; i < player.length; i++){
System.out.printf("%s %s\n", player[i].name, player[i].score);
}
}
}
Interesting question but I've never used this in my whole career.
If there is no public class in the source file then main method can
lie in any class and we can give any name to the source file.
Source: https://dzone.com/articles/why-single-java-source-file-can-not-have-more-than
Because of the remark of #Andy Turner, I tested it a little bit further and indeed you can have a main method in other classes (other than the public one). It all depends on how you call it:
package sample;
class Problem {
public static void main(String[] args) {
System.out.println("main of Problem");
}
}
public class Solution {
public static void main(String[] args) {
System.out.println("main of Solution");
}
}
The source file name must be Solution.java as this is the public class but you can call both main methods:
> java sample.Solution
main of Solution
> java sample.Problem
main of Problem
You can still call sample.Problem when you remove the main method from Solution.
While it's against "customs", it is possible to do what you tried. However the main() method is present in the Solution class, so that's the one you have to run.
From command line you can do that easily:
javac Checker.java
java Solution
as Solution.class will be generated properly.
However if you use an IDE, which you are not very familiar with, you may encounter difficulties when trying to tell them to run a different .class file from the .java they have just compiled. In short: name the file as Solution.java.

What wrong with my beginner code?

I cant understand whats wrong with my code. In this code i getting errors like this when im trying to assign a value to a variable within a class. Also System.out.println doesnt work in this classes:
1.Identifier expected
2.Unexpected token
3.Unknown class "windows"
public static void main(String[] args) {
}
class building{
int apart_num;
apart_num = 3;
}
class apartments{
double area;
int lightbulb;
int windows;
windows = 4;
}
interface construct_building{
}
interface construct_apartments{
}
You are declaring an instance member on one line :
int apart_num;
and then assign a value to it :
apart_num = 3;
The problem is that this is done outside a method, those statement can't be separated, you can't assign a variable previously declare outside a block statement so.
Do it in a one line (declaration and assignation) :
class building{
int apart_num = 3;
}
or with a constructor
class building{
int apart_num;
public building(){
apart_num = 3;
}
}
or in a block statement
int windows;
{ //a block statement
windows = 4;
}
Then, if this code is not a class, you need to do it.
public MyClass{
public static void main(String[] args){ ... }
...
class Building { //inner class (will exist only inside of a MyClass instance
}
static class Apartment { // a nested class, exist whitout a MyClass instance
}
}
class Level { //A class that have nothing to do with MyClass and that can not be public.
}
Where MyClass is the name of the file (MyClass.java)

How to use multiple classes in java in one file?

I want to know how to use multiple classes in one file in java. I typed this code but it is showing compilation errors.
class test {
int a, b, c;
void getdata(int x, int y) {
a = x;
b = y;
}
void add() {
c = a + b;
System.out.println("Addition = " + c);
}
}
public class P8 {
public static void main(String[] args) {
test obj = new test();
test.getdata(200, 100);
test.add();
}
}
You can only have one public top-level class per file. So, remove the public from all but one (or all) of the classes.
However, there are some surprising problems that can happen if you have multiple classes in a file. Basically, you can get into trouble by (accidentally or otherwise) defining multiple classes with the same name in the same package.
If you're just a beginner, it might be hard to imagine what I'm going on about. The simple rule to avoid the problems is: one class per file, and call the file the same thing as the class it declares.
The compilation errors in the classes you showed us have nothing to do with having two classes in the file.
public static void main(String[] args) {
test obj = new test();
test.getdata(200, 100); // error here
test.add(); // error here
}
When I compile your code using javac the error messages are:
$ javac P8.java
P8.java:21: error: non-static method getdata(int,int) cannot be referenced from a static context
test.getdata(200, 100);
^
P8.java:22: error: non-static method add() cannot be referenced from a static context
test.add();
^
2 errors
The problem is that test is a class name, not the name of a variable. As a result you are trying to invoke instance methods as if they were static methods.
But to my mind, this is a classic "I've shot myself in the foot Mum" moment.
You have broken one of the most widely observed rules of Java style.
Java class names should always start with an uppercase letter.
You have named your class test rather than Test. So when you wrote
test.getdata(200, 100);
test looks like a variable name, and that looks like a call of an instance method. But it isn't.
My bet is that this is part of what caused you to misconstrue the error message as being related (somehow) to having two classes in a file.
There is another stylistic howler in you code. You have called a method getdata but it actually behaves as a (sort of) setter for the Test class. If your code wasn't so small that it fits on a single page, that would be really misleading.
And finally, I agree with people who advise you not to put multiple top level classes into a single source file. It is legal code, but unnecessary. And style guides typically recommend against doing it.
i hope it will help you....
i just changed test.getdata() to obj.getdata()
and test.add() to obj.add() ..... check it out..
class test {
int a,b,c;
void getdata(int x, int y) {
a=x;
b=y;
}
void add() {
c=a+b;
System.out.println("Addition = "+c);
}
}
public class P8 {
public static void main(String[] args) {
test obj = new test();
obj.getdata(200,100);
obj.add();
}
}
you can not call test.getdata()..
and test.add()... as its not static methods
You can use at most one public class per one java file (COMPILATION UNIT) and unlimited number of separate package-private classes.
Compilation unit must named as public class is.
You also can have in your public class the unlimited number of inner classes and static nested classes.
Inner classes have an intenal pointer to the enclosing class so they have access to its members as well as local vars. They can be anonymuous.
Static nested classes is just like regular pubic class but is defined within enclosing class
Here's a very basic example of how to nest classes within classes. For this example, let's say that my file is named Test.java
public class Test {
public Test() {
}
class Person {
public Person() {
}
}
}
You should really take a look at how constructors work, because that may be one of your problems. Can't tell what else without more info, unfortunately.
{
// you have to call the method by the object which you are created. then it will run without error.
Test obj = new Test();
obj.getdata(20, 10);
obj.add();`
}
You have to nest your classes in each other, although it is not recommended.
public class P8 {//Currently inside P8 class
class test {//Declaring while inside P8
private int a, b, c;//Private vars in a nested class
void getdata(int x, int y) {
a = x;
b = y;
}
void add() {
c = a + b;
System.out.println("Addition = " + c);
}
}
public static void main(String[] args) {//Running the main for P8 class
test obj = new test();
test.getdata(200, 100);
test.add();
}
}
One of the reasons nesting classes is a bad idea is it strips the class of its privacy. The 'private' tag in java take whatever variable is tagged with it, and will only let that class access it, but if the class is inside another, both classes can freely access those private variables.

Java in BlueJ does not execute main class

I am using the BlueJ IDE. I have a main class entitled ProgramOne, and another class StarTurtle (intended to serve an instance method).
Here is the code of ProgramOne:
public class ProgramOne
{
public static void main (String[ ] args) {
StarTurtle turtle1 = new StarTurtle();
int result = turtle1.StartTurtle(5);
}
}
Here is the code of StarTurtle:
public class StarTurtle
{
private int points;
public int StartTurtle(int x)
{
points = x;
Turtle sue;
sue = new Turtle();
sue.paint (90, 40);
}
}
(The turtle method you see is from two other classes that I have not pasted here for the sake of brevity. These classes are found in the http://www.cs.ccsu.edu/~jones/book.htm manual)
The code only compiles, and there is no option to execute. However, there is no option to execute void main (String[ ] args), which there should be to execute the main class. Does anyone know what is the cause of this? I am assuming that there is a problem in the code itself. The StarTurtle class does execute, but the main class ProgramOne does not, which leads me to believe that the problem lies in the ProgramOne class.
When I mean "option to execute", I am referring to this BlueJ functionality:
When you call the main method from the class ProgramOne, you have created an instance of StarTurtle turtle1. But when you assign value in result variable by calling turtle1.StartTurtle(5) method, nothing is stored in that variable. The problem is that you have issue in this function in your StarTurtle class. You have defined public int StartTurtle(int x) function as return type but actually it is not returning any thing. Therefore, you need to add a return statement on that block of code.
public class StarTurtle {
private int points;
public int StartTurtle(int x){
points = x;
Turtle sue;
sue = new Turtle();
sue.paint (90, 40);
return points;
}
}
However, on the other hand, your class and functions are incorrect though they are working. You classes should be like this.
public class ProgramOne{
public static void main (String[ ] args) {
StarTurtle turtle1 = new StarTurtle();
turtle1.StartTurtle();
}
}
public class StarTurtle {
//Void type of method instead of previous return type
public void StartTurtle(){
Turtle sue;
sue = new Turtle();
sue.paint (900, 550);
}
}

Using a class with int in main()

I want to write a class with three int values in them and manipulate them in main();
There are two ways I can think of doing this
Have a seperate .class file and include it into another class file containint the main() function
stuff.java:
class stuff { ... }
class app {
public static void main(String[] arguments) {
.. // manipulate the instance variables
}
}
2 have the class and then a class containint the main function in the same file app.java
app.java:
class stuff { ... }
class app {
public static void main(String[] arguments) {
.. // manipulate the instance variables
}
}
Are these the main ways it is done in java ( I didn't see anything on including java classes ). Or can I make the stuff class contain main itself?
I am wondering, if you want to write a class with three int values in them and manipulate them in main() method just do it! Why do you need some staff class ?
You do not need to have two separate classes. You can simply place the main main in the same class that contains the instance variables.
class App {
int var1;
int var2;
int var3;
public static void main(String[] arguments) {
.. // manipulate the instance variables
App app = new App();
app.var1 = 1;
app.var2 = 2;
app.var3 = 3;
}
}
Edit: Bassed on your comment, you want to use have to objects to do this. If the classes are in the same package it is pretty simple.
Stuff.java
public class Stuff {
int var1;
int var2;
int var3;
}
App.java
class App {
public static void main(String[] arguments) {
.. // manipulate the instance variables
Stuff stuff = new Stuff();
stuff.var1 = 1;
stuff.var2 = 2;
stuff.var3 = 3;
}
}
This obviously an overly simplistic example, but should give you the general idea. If the App class is in a different pacakge you simply need to import the Stuff class by adding import pacakage.name.Stuff; at the top of the App class.
The classes are usually defined in .java files. When they are compiled, compiler will create a separate .class file for every class you defined. You can put multiple classes in single .java file; however, classes marked as public will require separate .java file.
You might consider inner class for your purposes

Categories

Resources