I am looking to add a function to a program where I use static variables to create a list of all the times the driver has used the constructor, using names. What I need to know is this, is there a way, in java, to access what the reference variable is (as a string) to add it to the list?
Pseudocode:
public ClassName
String static list = "";
Public ClassName (parameters){
list += getReferenceVariable();
}
The getReferenceVariable is what I'm asking if anyone knows a way to do that
If I understand you correctly, you want to keep a list of all the times the constructor was called, and save the names of the currently-being-created variable? Because the "Reference variable" is none when you use the constructor, since you call the constructor with a new MyClass(), and not some obj.MyClass().
If, however, you simply want to know who called you (As a stack trace is), you can simply, as written in this thread (no pun intended), use
Thread.currentThread().getStackTrace(), and then choose the desired stack frame (Probably 2, since The first element (index 0) in the array is the java.lang.Thread.getStackTrace method, the second (index 1) is the constructor, and 2 is where the constructor was called from), where you can get (for example) the name of the source file that this stack trace corresponds to. Documentation of getFileName()
Since I haven't tried it on my end (not possible at the moment), I give you code to use with caution:
public class MyClass(){
MyClass(){
callerName = Thread.currentThread().getStackTrace()[2].getFileName();
... // anything here
}
}
Related
I'm having issues with a concept from an assignment I'm working on
public class MyHugeInteger
{
MyIntList list = new MyIntList();
public int compareTo(MyHugeInteger hugeInt)
{
if (list.size() > this.list.size()) //this is where things don't work
return (-1);
if (list.size() < this.list.size())
return (1);
}
Basically, I need to be able to use the 'list' variable from the passed version of the object to be able to compare it to the list variable from the current object.
I had a similar problem to this before, and my professor responded with "objects of the same class can access each others' private data members. So you do have access to other.size from "this" and can check Set sizes for equality."
This is what I'm trying to use in the code given, but I found an example saying that this will call the field variable, the one already called by just saying 'list'
Am I missing something?
The comment was right, hugeInt.list.size() > this.list.size() instead of using 'this' for the passed object. One of those things that you miss when you're overthinking the problem
If you're trying to use the Java framework to sort things or use the compareTo method, as intended, you need to implements Comparable<MyHugeInteger> in your class.
public class MyHugeInteger implements Comparable<MyHugeInteger>
Then, to fix the error, you need to use the parameter object because this.list and the unqualified list are the exact same object.
Also consider what happens when sizes are equal.
Tip: don't need to rewrite the integer comparison logic yourself.
#Override
public int compareTo(MyHugeInteger hugeInt) {
return Integer.compare(this.list.size(), hugeInt.list.size());
}
Multiply by negative one or flip the parameters if you notice the ordering is wrong.
I am required to take all user input from within a void method (though it's important to note that the original verbiage says the method must not have a return value), and have all output be relegated to a separate method.
Now, I have all that set up and it's passing the relevant array to the sub method just fine (because I call the sub method from within the void method). But, I need the main to actually do the rest of the calling using the value from that sub method in other methods.
An in depth explanation and teaching would be deeply appreciated.
If you have luxury to change the signature of the methods (keeping the return type as void), you can pass another data structure to the methods. That way, you can get the user inputs inside GetUserInput(customDataStruct) method, pass it to SubMethod(customDataStruct) method. SubMethod() will modify the customDataStruct content, which will be available directly in main(), if main() invokes GetuserInput().
Second option, as #Fiddle suggested, is to use a global variable and let the methods manipulate it. This global variable shall be accessible from main().
I had it flipped. By letting the void method be the sub method and actually learning to pass by reference (enjoy my head smacking) I was able to use the method with the return to bring the value back to main.
I already tried to search for an answer on the "using the new keyword" but didn't found an answer on my specific question.
Why do some classes have to be created with the keyword new and some don't
For example :
import java.io.BufferedReader
If you want to use this you have to create a new instance
BufferedReader read = new BufferedReader (..............)
But for example with system.console which also needs an import java.io.console. when you want to use this you can just type Console c = system.console()
i'm a beginner in Java and OO programming and found a couple of this examples troughout my book.
Thx for the help
In java, fields(aka Attributes) are always associated to either instance or to class.
There could be many instances of a class and to create instance you have to use new operator. To access instance related attributes, you will need to create one and this will be accessed as
ClassName instanceName = new ClassName();
instanceName.methorOrAttributeNameGoesHere
For class associated attribute aka Static attribute can be direcly accessed as ClassName.methorOrAttributeNameGoesHere
These are very basics of Java and probably you should first read some good book on Java and OOP like 'Head First Java'
The simple answer to this is that instantiation like new BufferedReader() always creates a different instance each time you call it; invoking a method like System.console() might or might not give you different instance.
Ultimately, all objects are instantiated via new; you just might not see it in your code.
Here are a couple of ways in which System.console() might be implemented (totally simplified, not actually like it is):
// (1) Returns new instance each time
class System {
static Console console() {
return new Console();
}
}
or
// (2) Returns same instance each time
class System {
private static final Console CONSOLE = new Console();
static Console console() {
return CONSOLE;
}
}
(There are infinitely more ways to implement it, these are just two examples. You can see the way it is implemented in OpenJDK by looking at the source code - it is similar to (2), in that the same instance is returned each time, just with a few more complications that I don't want to describe here)
In (1), if you invoke System.console() twice, you will get back two different instances of Console:
System.console() != System.console()
In (2), if you invoke System.console() twice, you will get back the same instance of Console:
System.console() == System.console()
The question I would ask here is do I need to care if I get back different instances or the same instance? The answer is probably not, if the API designer has done a reasonable job.
The decision as to whether expose the creation of a new Console was made by the person who wrote the classes. There are a number of reasons why he/she might not want you to create a different instance each time you invoke that method, e.g.:
The thing you are creating might be very expensive (slow, takes up lots of resources etc), so you don't want to create lots of them;
The thing you want has logically just one instance (it is a singleton).
There are a number of reasons why he/she might want you to create a separate instance each time you invoke that method, e.g.:
You don't want all of the places using that instance to share state. You have to worry about things like thread safety when instances of mutable classes are shared.
And there are a number of reasons why you might not want the user to invoke the constructor directly:
new Console() creates an instance of Console exactly; things like consoles are often platform-dependent, so you might actually want an instance of WindowsConsole, MacConsole etc to be returned when run on Windows, MacOS etc. If WindowsConsole and MacConsole extend Console, either of these can be returned from the System.console() method.
Prior to the introduction of the diamond operator <> in Java 7, it was necessary to include the full generic parameters in the new statement, e.g. ArrayList<HashMap<String, List<String>>> list = new ArrayList<HashMap<String, List<String>>>();; however, generic methods allowed this to be written as ArrayList<HashMap<String, List<String>>> list = newList():
<T> List<T> newList() { return new ArrayList<T>(); }
(Sometimes, you need a lot of parameters to pass to the constructor, and it is convenient to use the Builder Pattern. This isn't relevant to the cases in the question, but it is a reason for not invoking the constructor directly.)
The thing is that these are internal implementation details, and should be encapsulated: you, as a user of the Console class, shouldn't need to care about how expensive it is to create, or whether there is shared state: you just want a Console.
This encapsulation is effected by providing a method like System.console(): you don't need to know whether the method is implemented like (1) or (2) above (or any other method).
Additionally, if the class is originally written like (1), and that proves to be problematic, its implementation can be changed to (2) without you, as a user of the System class, needing to update your code.
This might be a bit too much detail for a beginner, and I can try to help you understand more; the long and short of it is that sometimes it is be better if you don't create instances directly.
System.console,console is static thats why we are calling it with class name directly,and to call the non static method we generally used the objectname.methodname .
The java.io.Console class is attached with system console internally.System class provides a static method console() that returns the unique instance of Console class.Thats why we used to do as Console c = system.console();
Please read about Static classes and non static classes method invocation/instance creation for more details.
Static methods don't require an instance, but non-static methods do. System.console() is static, butnew BufferedReader(...).read(...) is not
Static methods are typically used when the outcome of the method will never change based on the context. For instance:
Math.abs(-3); //will always be 3, no matter what
However consider this class:
public class Person {
private String name;
public Person(String name){
this.name = name;
}
public String getName() {
return name;
}
/*
* In this world, no special characters are allowed in a person's name
*/
public static boolean isValidName(String name) {
if (name.contains("!#$%&(=?") {
return false;
}
return true;
}
}
Person mySister = new Person("Mary");
Person myBrother = new Person("David");
Calling Person.getName() doesn't make any sense; this is like asking "What is a person's name?" without specifying who the person is. Now if you ask me "What is your sister's name?", then I can call mySister.getName() and give you a sensible answer.
Re: your comment "how do you know when to not use new"
If you are trying to create a new Person object (imagine you just had a baby), but you are wondering whether or not that amazing name you found on the internet will be accepted by the authorities:
boolean validName1 = Person.isValidName("LordVoldeMort!!!!!"); //returns false
boolean validName2 = Person.isValidName("HarryPotter2016"); //returns true
Person myLittleBabySon = new Person("HarryPotter2016"); //Accepted by authorities
I'm trying to get a better understanding than I've been able to so far...it's to help me with class, but not with any specific homework assignment; I'm looking for more conceptual information that I've not found in my textbook or in the tutorials. On a purely theoretical level, I get why encapsulation is powerful for OO programming, but need a better understanding of what, specifically is going on. I keep confusing myself about the path through which data flows, and wonder where we're getting and setting data FROM. Hopefully this is not the exception to the "there are no stupid questions" rule.
Consider:
public class Employee
{
private int empNum;
public int getEmpNum()
{ return empNum; }
public void setEmpNum(int Emp)
{ empNum = emp; }
}
My interpretation of this: Using int Emp passed from somewhere, we set the declared empNum variable in the set... method. We then get... that variable and return it to the calling method. Is that a good understanding?
Further Consider:
import.javax.*
public class CreateEmp
{
public static void main(String[] args)
{
int ssn;
ssn = JOptionPane.showInputDialog(null,"enter ssn");
Employee newEmp = new Employee(123456789);
JOptionPane.showMessageDialog(null,"Employee ID " + newEmp.getEmpNum);
}
}
With this class, I don't need to explicitly set a variable because declaring new Employee(123456789) automagically sends that value to the set... method. The return in the Employee method returns the resulting value to the calling method and makes that variable available, in this case to my dialog box output. Do I have a handle on that?
Here's where I get confused. With my understanding as noted above--which may be off--I can never decide the best place to put logic. For instance: I would place the "enter employee number" dialog box in the Employee class, with a condition to run ONLY if the parameter passed to the method was null. In my mind, as I understand the data flow, the purpose of the class is to get an employee number. If one is not supplied as a default, one needs to be created. I'm not sure if this thinking is best practices, or if I'm setting myself up for trouble later.
I'd love to hear some thoughts about whether or not I'm properly understanding what's happening.
First, this site is to be used more for questions that can be concretely answered; not so much for theoretical questions.
Anyways, the first part with the 'get' and 'set' you understand fine. Now when you said that you do not need to explicitly set the employee number because you do 'new Employee ...' is not quite true. That would work if you had explicitly defined a constructor that takes an integer for an argument and then sets 'empNum' equal to the argued integer value.
Getters and setters are usually used in conjunction with the 'private' modifier. Setters can be used to control the input. For example, you can check if the provided value is greater than zero, where as you cannot if you give direct access. Getters just allow values to be retrieved, but to make changes you force the use of the corresponding setter (if any).
You are right about how if a value is not supplied you should set one by default. Consider that the value that you retrieve (if any) is to be used in a different class. What if the user never set a value? What if it's not something you expected? The different class, whatever it may be, still requires a value and you still need to pass something. By setting a default value, the different class can recognize that, "oh, this is a default value - this means that the user probably did not supply the correct input." By doing so, you create a relatively fail-safe application; you can keep on working even if the input is not what it is expected to be.
The point of using public accessors for private variables is to control how those variables are accessed and to insure that all of the internal state is kept consistent. For example, a class might have both an age and a birthdate variable. Setting the birthdate also implicitly sets the age. If direct access was given to these variables, then it would be possible to set them to inconsistent values (i.e. birthday says they are 30, but age set to 35). By using setters, we can insure that setting the birthdate will reset the age to be correct.
In this example, using setters would also allow us to convert the age variable into a generated property. Since age can be directly determined using the birthdate, you can create a getter for age and have it directly calculate and return the age without needing to store it anywhere.
If we use getters and setters to expose these object properties, we are free to switch out the implementations (such as removing the age variable and calculating it on the fly) without the users of our object needing to worry about it.
It depends how you are using the Employee object. If, upon construction, you always provide the employee number or one is automatically provided and the employee number is never set anywhere else, then you won't need the set method.
However, if at some point you are going to set the employee number to something else (perhaps an error was made and the number needs to be updated), then you will need to have a "set" method. In this case, it would probably be easiest to also call the "set" method from the constructor.
It really depends on how the Employee class will be used/instantiated.
You say
With this class, I don't need to explicitly set a variable because declaring new Employee(123456789) automagically sends that value to the set... method.
I'm pretty sure that's not true. Consider this: Java creates an Employee object and the constructor receives the value 123456789. How does it know to which variable it needs to assign that value? It doesn't know. There can be multiple variables that belong to that object so it doesn't know what 123456789 really means.
When you don't define a constructor in Java, it automatically creates one for you. But that one does not take any arguments, it's just a default constructor. Your code has several compile errors (for example, the import line for javax is wrong) so I'm guessing you're running a previously compiled version of your code. Remove all .class files in your project, fix compile errors and run again. It should give you an error. It'll also make the flow of data a lot easier to understand. The constructor should look something like this:
public Employee(int empNum) {
this.empNum = empNum;
}
It now makes a lot more sense that getEmpNum() knows which value to return.
With this class, I don't need to explicitly set a variable because declaring new Employee(123456789) automagically sends that value to the set... method. The return in the Employee method returns the resulting value to the calling method and makes that variable available, in this case to my dialog box output. Do I have a handle on that?
Your understanding is slightly wrong here. The statement
new Employee(123456789)
is creating a new Employee object by using a constructor method. Constructors usually take parameters which are used to set the internal member variables of the class.
So the complete Employee class would be -
public class Employee
{
private int empNum;
public Employee(int employeeNum) {
empNum = employeeNum;
}
public int getEmpNum() {
return empNum;
}
public void setEmpNum(int Emp) {
empNum = emp;
}
}
I would like to know if the following code should work:
if (M != 0){
Tools.Printer(stdnr);
}
Background Info:
I created a public class Tools with a few functions. One of the functions is the void Printer function. Is there a rule or something that if you want to use Tools.something you need to do assign the Tools.something to an integer / print it, etc. Or is Tools.Printer supposed to work on its own.
I ask this because I can't find anything wrong with my code. I would be glad if someone can help me right with the terms I used above - I suppose they are terribly wrong...
Thank a lot, Help would be greatly appreciated
If your method is a void type, it returns nothing, therefore you do not need to assign it to a variable (in fact, you'll get a compile time error if you do).
If it was instead a function, like it returned some value, for instance:
public String foo()
{
return "kdfldj";
}
You still don't necessary need to assign it to a variable. The returned value will just be discarded. For example, StringBuilder.append returns back the StringBuilder that you just appended to, but you can safely call it like this:
myStringBuilder.append("some text");
And ignore the return value.
However, if your Tools.Printer method is not a static method, you do need to create an instance of Tools, either assigned to a variable like this:
Tools tools = new Tools();
tools.Printer(stdnr);
or initialized without being placed in a variable:
new Tools().Printer(stdnr);
But if Printer is a static method, your code should be fine, since you are calling the method by the class it's contained in.