I am trying to see the basics for what is required to call in a second class, because tutorials and the book I am using are over-complicating it by using user input right now.
So here is what I tried. First is my main class and the second is the class I tried to call into the main method portraying just a simple text.
public class deck {
public static void main(String[] args) {
edward test = new edward();
System.out.print(test);
}
}
Other class:
public class edward {
public void message(int number) {
System.out.print("hello, this is text!");
}
}
How come this doesn't work?
If you could try to explain what I am doing or how this works a bit in detail that would be nice. I'm having a hard time with this part and getting a bit discouraged.
This does not work because you are printing a wrong thing: rather than printing test, you should call a method on it, like this:
public class deck {
public static void main(String[] args){
edward test = new edward();
test.message(123);
}
}
message(int) is a method (more specifically, an instance method). You call instance methods by specifying an instance on which the method is to be called (in your case, that is test), the name of the method, and its parameters.
The other kind of methods is static - i.e. like main. These methods do not require an instance, but they cannot access instance properties either.
Just an additional hint.
Every class in Java is derived from the java built in class "Object".
This common class offers some common methods.
In your case the method
public String toString()
is from interest.
You can override this method in your class edward and return the String you want.
public class edward {
#override
public String toString() {
return "hello, this is text!"
}
}
If you now use an object of class edward (test)t within the main method like you did it in your sample code
public static void main(String[] args) {
edward test = new edward();
System.out.println(test);
}
Then the text returnrd by the overriden toString() method would be printed out.
You use in this case the possibility to override methods from a super class (Object) and a subclass (edward).
Generally you would use the toString nethod to output the values of the fields (properties) of an object to show its current state.
If you not override the toString method you would get a String like eg this #ae23da which represents the current adress of the object test in memory.
public class deck
{
public static void main(String[] args)
{
edward test = new edward(); //1
System.out.print(test); //2
}
}
In line 1, you create a new edward object called test.
In line 2, you print the object itself. According to the Java API, print(Object)
Prints an object. The string produced by the String.valueOf(Object) method is translated into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.
I'm guessing that the output looked something like: edward#672563. That is because String.valueOf(obj) returns the type of obj (edward), followed by the character #, followed by the location in memory of obj (672563).
Here is some code that should do what you are attempting:
public class Deck //all class names should be capitalized
{
public static void main(String[] args)
{
Edward test = new Edward();
test.message(); //1
}
}
public class Edward
{
public void message() //`message` doesn't need a parameter
{
System.out.print("hello, this is text!");
}
}
In line 1, you call test's method message(). Calling a method executes the code that is in that method, so test.message() executes the line
System.out.print("hello, this is text!");
Here is a different way of doing the same thing:
public class Deck
{
public static void main(String[] args)
{
Edward test = new Edward();
System.out.println(test.message); //1
}
}
public class Edward
{
public String message = "hello, this is text!"; //2
}
In line 2, you create a new String "field" with the value of "hello, this is text!".
In line 1, you print the value of the field message contained in the object test.
If there are other parts of this code that you don't understand, feel free to comment on this answer!
Related
Is it able to avoid using "static" when call variable from another class? thank you very much
Here is my code.
class Hello {
public static String say = "Hello World"; //I using static
public void born() {
System.out.println(say);
}
}
public class SayHello extends Hello {
public static void main(String[] args) {
Hello myHello = new Hello();
myHello.born();
System.out.println(say);
}
The Output:
Hello World
Hello World
If I use public String say = "Hello World";
it output Hello World null
AnyIdea to avoid using "static" when call variable from another class?
thank you very much
If you remove the static, it will not compile. Static fields can be marked private, if you want to hide them. So then they are reachable by all instances of the class Hello only. The proper way of modifying or getting would be:
class Main extends Hello {
public static void main(String[] args) throws Exception {
Hello myHello = new Hello();
myHello.born();
// System.out.println(say); //doesn't allow access
// System.out.println(Hello.say); //doesn't allow access
System.out.println(myHello.getSay());
}
}
class Hello {
private static String say = "Hello World"; //private
public void born() {
System.out.println(say);
}
public String getSay() {
return say;
}
}
A static variable is common to all the instances (or objects) of the class because it is a class level variable. In other words you can say that only a single copy of static variable is created and shared among all the instances of the class.
So if you don't want to use static, then you can't use it in the other instances of class.
Yes, if you don't declare it static you can reference it from an instance: myHello.say.
It is the same as for calling a function.
public class SayHello extends Hello {
public static void main(String[] args) {
Hello myHello = new Hello();
myHello.born();
System.out.println(myHello.say);
}
}
For a constant, ie. a String that never changes and is the same for all instances of the class, it makes sense to declare it static and use it as such.
If you don't mark the string as static you will get a compilation error because when you do System.out.println(say) in the main method you are using say in a static context (since the main method must be static).
If you remove System.out.println(say); and just leave myHello.born(); then there's no need for say to be static because you'll only be using it from non-static methods (i.e. the born() method). You can see it in this example where I commented that line and defined say as not being static.
Another option would be to make the println like this, since the variable is public: System.out.println(myHello.say);
public class test extends AbstractTableModel {
public static void main(String[] args) {
}
public String valuePass(int rowIn)
{
String value = "open";
return value;
}
test(mdpTEST parentPanel) {
m_parentPanel = parentPanel;
}
...
}
import demo.test;
public class order{
public void new()
{
test blah = new test(null);
String text = blah.valuePass(0);
}
}
In the code above, "blah" should be referencing the class "test" which is public, however I'm told to change the visibility of "test()" to public as I get an error in the line: "test blah = new test(null);". I'm confused at why "public class test" is not being referenced by "blah" and how the second instance of "test()" is being utilized here. I appreciate any help in understanding this problem!
Two issues with the code that you have shown
1) You cannot have new() as method name as new it is a keyword
2) Line test blah = new test(null); is calling a constructor of a test class which is in a different package. So default visibility is applied to test(...) constructor in test class. And as per java visibility rule, you have to make it public to access it in a different package
Do these changes and your code should work fine
I'm new to Java and is trying to learn the concept of inner class. I saw the code below from Java tutorial Oracle. My question is, for
String name = "world";
#Override
public void greet() {
greetSomeone("world");
}
Can greetSomeone("world") be replaced by greetSomeone(name). The reason why I'm asking this question is because I have noticed if greetSomeone("world") is indeed replaced by greetSomeone(name), inside the public void greetSomeone() method, the passed "name" argument will be set to itself. I was just wondering if there are side effect to code like this?
public class HelloWorldAnonymousClasses {
interface HelloWorld {
public void greet();
public void greetSomeone(String someone);
}
public void sayHello() {
class EnglishGreeting implements HelloWorld {
String name = "world";
#Override
public void greet() {
greetSomeone("world");
}
#Override
public void greetSomeone(String someone) {
name = someone;
System.out.println("hello " + name);
}
}
HelloWorld eg1 = new EnglishGreeting();
eg1.greet();
}
public static void main(String[] args) {
HelloWorldAnonymousClasses myApp = new HelloWorldAnonymousClasses();
myApp.sayHello();
}
}
First of all why is that #Override annotation there?
You will use Override when you want to change the behaviour of the parent's methods. Your parent's methods have no behaviour as it is an interface. As a further note I guess that it will teach you that the signature of an overriden method must always match the one from the parent.
Secondly the design is kind of dodgy. It can be simplified.
Thirdly yes you can refer to the String object name as it is defined in that class and you can access the object's primitive just by calling 'name'. Why will you not get the reference printed when System.out? Because the String object handles that for you ensuring the toString will show you the primitive. When you do System.out.print(myObject); The console will show you the Object default or the overriden toString method.
So if you create an object and you do System.out.print(myObject) you will see the reference. If you override toString returning "test" you will see test.
Technically, name can be passed and name = name; is valid Java.
However, this is a horrible design and was probably used for demonstrative purposes only. Don't do this.
I have three classes.. A,B,C.
In both classes B and C i have a static string variable "name" which contains the name of B and C, as-
class B
{
static name;
public static void main(String args[])
{
name="Class B";
A.getName();
}
I am calling class A's getName method from class B and C.. Class A is as follows:
class A
{
getName()
{
System.out.println(this class called me);
}
}
class C is:
class C
{
static name;
public static void main(String args[])
{
name="Class C";
A.getName();
}
Now my question is, what code should i use in place of "this class called me" in class A so that i get the name of whichever class calls A! I hope i am clear!!
Your A.getName method cannot know what class's code called it. You have to pass that information into it.
Okay, so that's not strictly true, you could figure it out by generating a stack trace and inspecting that. But it would be a very bad idea. In general, if a method needs to know something, you either A) Make it part of an instance that has that information as instance data, or B) Pass the information into it as an argument.
class A {
getName()
{
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
int lastStackElement = stackTraceElements.length-1;
String callingObjectsName = stackTraceElements[lastStackElement].getClassName();
System.out.println(callingObjectsName + " called me.");
}
}
Modify your code to something like this:
class A
{
getName(String className)
{
System.out.println(className);
}
}
and use it like :
class B
{
static name;
public static void main(String args[])
{
name="Class B";
A.getName(name);
}
}
It sounds like what you're really trying to do is to pass information from one stack frame to another one -- and specifically, from a frame A to a frame B, where A invoked B. This is an easy thing to do, and I think you're over-engineering it.
public class B {
static String name = ...
public static void main(String[] args) {
A.getName(name);
}
}
public class C {
static String name = ...
public static void main(String[] args) {
A.getName(name);
}
}
public class A {
public static void getName(String name) {
System.out.println(name);
}
}
Your approach would require:
Getting the stack trace
Using that to get the calling stack frame, which is element 1 in the stack trace array
Using that to get the class name for the calling method
Using Class.forName to get the Class<?> object
Calling getField("name") on that Class<?> object to get a Field object
(optional but recommended) Confirming that the Field represents static field of type String
calling get(null) on the Field to get its value (the null represents the object for which you want the field -- since the field is static and thus not tied to any object, this argument is ignored), and casting this value down to String
Or, instead you could:
Just pass the name to the function that needs it.
Your approach also requires that the name field be static, since there's no way to get the calling instance (even though you can get the calling instance's class). The simpler approach works even if name is an instance field.
Basically, I need to create a new simple Java class which retrieves values from my forms (that I have designed as my process and is deployed as a web application), once the method in the Java class is invoked then the Java class should just simply print out the values (e.g. system.println.out...) it got from the form in a console or text file.
Create a class with some instance parameters. Print a line stating the initial values of these parameter(s).
I am new to Java and have just started few days ago but have this requirement as part of a project.
Please someone help to write this Java class.
I recommend you to read some java beginners books (or the javadoc) in order to understand the Class constructor concept in java before trying to do write something wrong.
A rough class may be like this :
public class myClass{
int param1;
int param2;
public myClass(int firstparam, int secondparam){
this.param1 = firstparam;
this.param2 = secondparam;
}
}
public static void main(){
myClass c = new myClass(1,2);
System.out.println(c.param1 + c.param2);
}
If you don't understand this, please learn the java basis..
You can simply create a class and its constructer like:
public class Test {
//a string representation that we will initialize soon
private String text;
//Firstly you have to instantiate your Test object and initialize your "text"
public Test(String text) {
this.text = text;
//System.out.println(text);
//You can print out this text directly using this constructor which also
//has System.out.println()
}
//You can just use this simple method to print out your text instead of using the
//constructor with "System.out.println"
public void printText() {
System.out.println(this.text);//"this" points what our Test class has
}
}
While using this class is like:
public class TestApp {
public static void main(String[] args) {
Test testObject = new Test("My Text");
/*if you used the constructor with System.out.println, it directly prints out
"My Text"*/
/*if your constructor doesn't have System.out.println, you can use our
printText() method //like:*/
testObject.printText();
}
}