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
Related
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.
I'm making a game where players have to write their own class to control the on-screen units. However, I want to prevent them from using static variables inside the player class so that their units have to communicate information via a communication system I have developed (i.e transmitting 1s and 0s) rather than just accessing the static "unitsTargeted" variable or whatever else it might be. Can I prevent them from using static modifiers somehow?
That depends. If you have no control over the source code or the run environment, then you cannot stop them from compiling what they want nor from having that executed.
If you have control over the build (ie: the source gets sent to a system you controlled and you control the compilation), then you could build a custom compiler.
If you control the run environment in some fashion, you could inspect the supplied class to see what it contains. You could use some byte-code tool, or better yet just use reflection API and check if any of the members are static. Once you use reflection to get a list of members, iterate over them and check their isStatic. If the class contains any static members, you could reject it.
In your case, since you are uploading classes to a server from clients, you could check it simply by using Java's reflection API. If the clients are submitting source code, then you will need to compile it first, though I assume you do that anyway before you use it.
Here is a test case I just ran:
package test.tmp;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
public class StaticChecker
{
public static void main(String[] args)
{
for(Class c : new Class[]{StaticChecker.class, ClassWithStatics.class, ClassWithoutStatics.class})
{
System.out.println("For " + c + "...");
boolean hasStatic = hasStaticMembers(c);
System.out.println("\tIt contains static members: " + hasStatic);
if(hasStatic)
{
System.out.println("\tThe static members are:");
for(String s : checkStaticMembers(c))
System.out.println("\t\t" + s);
}
}
}
public static boolean hasStaticMembers(Class c)
{
return checkStaticMembers(c).size() > 0;
}
public static List<String> checkStaticMembers(Class c)
{
List<String> staticMemberNames = new ArrayList<String>();
for(Field field : c.getDeclaredFields())
if(Modifier.isStatic(field.getModifiers()))
staticMemberNames.add(field.toString());
for(Method method : c.getDeclaredMethods())
if(Modifier.isStatic(method.getModifiers()))
staticMemberNames.add(method.toString());
return staticMemberNames;
}
}
class ClassWithStatics
{
public static int N = 3;
private static String S = "?";
private int n;
void f() { System.out.println("f()"); }
static void g() { System.out.println("g()"); }
public static void h() { System.out.println("h()"); }
}
class ClassWithoutStatics
{
int a;
String b;
void f() { System.out.println("f()"); }
}
When I run the above test, I get the following output:
For class test.tmp.StaticChecker...
It contains static members: true
The static members are:
public static void test.tmp.StaticChecker.main(java.lang.String[])
public static java.util.List test.tmp.StaticChecker.checkStaticMembers(java.lang.Class)
public static boolean test.tmp.StaticChecker.hasStaticMembers(java.lang.Class)
For class test.tmp.ClassWithStatics...
It contains static members: true
The static members are:
public static int test.tmp.ClassWithStatics.N
private static java.lang.String test.tmp.ClassWithStatics.S
static void test.tmp.ClassWithStatics.g()
public static void test.tmp.ClassWithStatics.h()
For class test.tmp.ClassWithoutStatics...
It contains static members: false
Please note that what you are doing can be dangerous and you should be very careful to limit what code executed server-side can do. All someone needs to do to ruin your day is submit a class which deletes files or installs unwanted files or any other nefarious action.
Do not to use static variable in your program, or if you really need one, make it ThreadLocal and keep it on a thread which is not accessible from the user classes.
If you want your program to be relatively safe you should also build some kind of class validator which will make sure those classes use only allowed classes, a very short white list of allowed classes.
You can use ASM to make such validator.
This question already has an answer here:
Import custom Java class
(1 answer)
Closed 9 years ago.
I am a beginner at java, I used to code in C++ and there when using classes I used to define them in separate files and then include those classes in my main file.
I'm trying to learn threads for socket programming so I can open multiple server ports as threads and accept multiple clients. I know that in Java the file name should be the same as the class name (correct me if i am wrong). This is what I am trying to do:
main.java
include derived.java;
class main1
{
main1()
{
System.out.println("Constructor of main1 class.");
}
void main1_method()
{
System.out.println("method of main 1 class");
}
public static void main(String[] args)
{
main1 my = new main1();
Derived derivedThread = new Derived();
derivedThread.start();
}
}
derived.java
public class derived extends Thread
{
public void run()
{
System.out.println("starting a new thread");
}
}
How can I create a derived class object in main and include it in my main1.java file?
I think I do not fully understand how classes work in Java and what classpath has to be used with it. I have a deadline for my networking project and I am very behind so please help me!
Delete your files and try this, this is how it should look in Java:
Derived class: Derived.java
public class Derived extends Thread {
public void run() {
System.out.println("starting a new thread");
}
}
Main1 class: Main1.java
public class Main1 {
public Main1() {
System.out.println("Constructor of main1 class.");
}
void main1_method() {
System.out.println("method of main 1 class");
}
public static void main(String[] args) {
Main1 my = new Main1();
Derived derivedThread = new Derived();
derivedThread.start();
}
}
Note:
1) Class names are always capitalized, and you are right, the filename must be the same. In addition, the constructor and any calls to the constructor must be capitalized.
2) If you put classes in the same package, you don't need to import them. If you have multiple packages, you would import like so: import packageName.className;. No need for .java at the end, strictly the class name. You can also have nested packages, so you might see things like: import java.util.ArrayList;. This would be using ArrayList class, found in the util package, which is in the java package (built in). You shouldn't have to worry much about making nested packages on smaller projects, but that's the concept.
3) Notice I added the public modifier to Main1 and it's constructor. It is good practice to give a modifier to class names and methods, as well as class variables. See this SO Question for information about modifiers. For a beginner, you should mostly only be concerned with public and private.
I hope that helps, and good luck with your Java studies.
No need to use this include derived.java; .Use import if the derived class exist in different package.The class Derived is different while calling and declaring.
class main1 // Class name must start with Uppercase
{
public static void main(String[] args)
{
main1 my = new main1(); // Can be remove
Derived derivedThread = new Derived();
derivedThread.start();
}
}
public class derived extends Thread // Change derived to Derived
--------------------^
{
public void run()
{
System.out.println("starting a new thread");
}
}
I have remove constructor and one method which is not used.
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.
I have two packages inside my project, a and b.
a is my "main class" that runs when the program runs but I need to make b run from a (if that makes sense).
I'm sure its something along the lines of PackageB.BMain but I'm not sure.
Edit:
Okay so I've learned a few new things, to start my main project is RevIRC, inside that I have two packages, MainChat and RevIRC, now when I run the program RevIRC is ran, I need to make Mainchat run when RevIRC is ran.
Like I said before I'm sure its something along the lines of RevIRC.MainChat.ChatMain() but I can't seem to figure it out.
You have 2 options:
Either create a new instance of B from A, like so: PackageB.BMain b = new PackageB.BMain();
Access the methods in BMain in a static way like so: PackageB.BMain.someMethod();`
Note that you can use either of these exclusively or mix them up together, however, it all depends on how you have written your BMain class.
So for instance:
package PackageB
public class BMain
{
public BMain()
{ }
public void foo()
{
System.out.println("This is not a static method. It requires a new instance of BMain to be created for it to be called");
}
public static void bar()
{
System.out.println("This is a static method. It can be accessed directly without the need of creating an instance of BMain");
}
}
Then in your main class (the class which has the main method):
package PackageA
public class AMain
{
public static void main(String[] args)
{
PackageB.BMain.bar();
PackageB.BMain bInstance = new PackageB.BMain();
bInstance.foo();
}
}
If you have two main methods it will either run from A or B. The JVM will choose the first main method it sees IIRC.
Have a standalone class that will have main. And create your classes there.. ?
import a.Class1;
import b.Class2;
public class MainController
{
public static void main(String args[])
{
Class1 class1 = new Class1() ;
Class2 class2 = new Class2() ;
//Both class no start at the "same" time.
}
}
if i am not wrong you want to run main method of class B from class A.
That you can call using B.main(arg[]);
eg :
package a;
public class A
{
public static void main(String[] args)
{
System.out.println("This is main method of class A");
B.main(null);
/*pass any args if you want or simply set null arg*/
}
}
package b;
public class B
{
public static void main(String[] args)
{
System.out.println("This is main method of class B");
}
}
i hope this simple example will clear your doubt.
you can refer to link which contains Java tutorial for beginners.