I am just learning Java as a hobby.
How do I make a class define a field? E.g.
private string[] biscuitlist
Thank you for any help provided.
Java is case sensitive. You need to declare it as String[], not as string[].
package yourpackage;
public class YourClass {
private String[] biscuitlist;
}
That said, this is actually not "subclassing". So your question title actually contradicts with the question message. To learn more about Java in general, I strongly recommend to go through the Trails Covering the Basics. Good luck.
The declaration goes inside the class definition as well.
public class SomeClass {
private String[] biscuitlist; // declare the variable
public SomeClass(){} // empty constructor
public String[] getList() {
// the variable is private so provide a getter for external access
return biscuitList;
}
}
If you declare the variable private only methods inside the class can access it. Checkout access controls to understand this if you need to.
You have defined variable already. Just note,
Java is case sensitive.
All classes starts uppercase, e.g. String, Date, List, etc by convention.
A class is basically a set of data (fields) and a bunch of operations(methods) on those fields
public class yourClass{
//define fields here
private String[] biscuitlist;
// java will automagically set biscuitlist to a null reference
//make a constructor for your class if it will ever be instantiated
public yourClass(){
}
//do stuff here (methods)
}
So basically defining a field is as simple as typing in the access(public, private, protected) giving it a type (String, int, String[], Object) and giving it a name. if not assigned a value after they will default based on the java API (objects get a null reference, ints get 0 etc.)
Related
I would like to know where to put constants which is only used in one java class? My code creates a name for a shared memory says "sharedMemory" , but I am not sure if I should put in separate Java file or just define in the same class as private static final String SHARED_MEMORY = "sharedMemory". I need this variable only in specific class. Also,if i define in same class should i make it static?
class ABC{
private static final String SHARED_MEMORY = "sharedMemory"; // OK to define in same class or in separate constants file
public void get(){
String name;
if(checIfSharedMemoryNeeded()){
name = SHARED_MEMORY;
}
}
private boolen checIfSharedMemoryNeeded(){
return (x.equals("yuiyr") && y.equals("yweir"))
}
}
Define constants that you only need in a single class in that class and make them private. You can make sure it will not accidentally be used anywhere else.
private static final String ONLY_FOR_THIS_CLASS = "only here";
Define constants that are contextually bound to a specific class but may be needed in other classes in that class they are contextually bound to, but make them public.
public static final String CONTEXTUALLY_FOR_THIS_CLASS_BUT_USABLE_ANYWHERE = "everywhere";
It will allow the usage in other classes like
String constantValueFromOtherClass = OtherClass.CONTEXTUALLY_FOR_THIS_CLASS_BUT_USABLE_ANYWHERE;
Think about writing an enum if the idea of a class that only holds public constants comes to your mind. In many cases, enums will be the better solution.
There are no common guidelines for what to do. Since it only used at one place, I recommend you to leave it in the class where it is used.
Unless you want to change the value in the future and you have many other hardcoded values that you want to change later, then I recommend that you make a class Config that holds all these values.
If this constant is only used for this class, then you should declare are the same class scope.
Now you gotta think if you are going to change the value in the future. If you do, and your application scales, it is better to create a .properties file to hold all the values and load to your app.
The general convention for non-global constants in Java is to write it with private static final like so:
class Foo {
private static final String bar = "foobar";
...
}
If you want to use this variable (SHARED_MEMORY) in ABC class then private access specifier is okay, and if this variable is part of your class not object then using static is a good idea.
Consider the following example code
class MyClass {
public String var = "base";
public void printVar() {
System.out.println(var);
}
}
class MyDerivedClass extends MyClass {
public String var = "derived";
public void printVar() {
System.out.println(var);
}
}
public class Binding {
public static void main(String[] args) {
MyClass base = new MyClass();
MyClass derived = new MyDerivedClass();
System.out.println(base.var);
System.out.println(derived.var);
base.printVar();
derived.printVar();
}
}
it gives the following output
base
base
base
derived
Method calls are resolved at runtime and the correct overridden method is called, as expected.
The variables access is instead resolved at compile time as I later learned.
I was expecting an output as
base
derived
base
derived
because in the derived class the re-definition of var shadows the one in the base class.
Why does the binding of variables happens at compile time and not at runtime? Is this only for performance reasons?
The reason is explained in the Java Language Specification in an example in Section 15.11, quoted below:
...
The last line shows that, indeed, the field that is accessed does not depend on the run-time class of the referenced object; even if s holds a reference to an object of class T, the expression s.x refers to the x field of class S, because the type of the expression s is S. Objects of class T contain two fields named x, one for class T and one for its superclass S.
This lack of dynamic lookup for field accesses allows programs to be run efficiently with straightforward implementations. The power of late binding and overriding is available, but only when instance methods are used...
So yes performance is a reason. The specification of how the field access expression is evaluated is stated as follows:
If the field is not static:
...
If the field is a non-blank final, then the result is the value of the named member field in type T found in the object referenced by the value of the Primary.
where Primary in your case refers the variable derived which is of type MyClass.
Another reason, as #Clashsoft suggested, is that in subclasses, fields are not overriden, they are hidden. So it makes sense to allow which fields to access based on the declared type or using a cast. This is also true for static methods. This is why the field is determined based on the declared type. Unlike overriding by instance methods where it depends on the actual type. The JLS quote above indeed mentions this reason implicitly:
The power of late binding and overriding is available, but only when instance methods are used.
While you might be right about performance, there is another reason why fields are not dynamically dispatched: You wouldn't be able to access the MyClass.var field at all if you had a MyDerivedClass instance.
Generally, I don't know about any statically typed language that actually has dynamic variable resolution. But if you really need it, you can make getters or accessor methods (which should be done in most cases to avoid public fields, anyway):
class MyClass
{
private String var = "base";
public String getVar() // or simply 'var()'
{
return this.var;
}
}
class MyDerivedClass extends MyClass {
private String var = "derived";
#Override
public String getVar() {
return this.var;
}
}
The polymorphic behaviour of the java language works with methods and not member variables: they designed the language to bind member variables at compile time.
In java, this is by design.
Because, the set up of fields to be dynamically resolved would make things to run a bit slower. And in real, there's not any reason of doing so.
Since, you can make your fields in any class private and access them with methods which are dynamically resolved.
So, fields are made to resolved better at compile time instead :)
I am reading a tutorial form this site.http://tutorials.jenkov.com/java-unit-testing/matchers.html
The author I believe is very experienced. I saw the code like this. I also saw someone else always like to assign the parameter of a method to a variable then use it inside the method. This one here is this line. protected Object theExpected = expected;
Can anyone please tell me, what is the benefit of this coding style? Is this trying to avoid the object status being changed or something?
What if the parameter is not an Object but a primitive variable.
And what if it is a immutable Object like String. Thank you.
public static Matcher matches(final Object expected){
return new BaseMatcher() {
protected Object theExpected = expected;
public boolean matches(Object o) {
return theExpected.equals(o);
}
public void describeTo(Description description) {
description.appendText(theExpected.toString());
}
};
}
Here is the update
I just did another test, to see if this parameter still accessible after we got the object.
package myTest;
public class ParameterAssignTest {
public static void main(String[] args) {
MyInterface myClass = GetMyClass("Here we go");
System.out.println(myClass.getValue());
System.out.println(myClass.getParameter());
}
public static MyInterface GetMyClass(final String myString){
return new MyInterface() {
protected String stringInside = myString;
#Override
public String getValue() {
return stringInside;
}
#Override
public String getParameter() {
return myString;
}
};
}
}
Output:
Here we go
Here we go
So does this mean that even we do assign this parameter to the a local variable it still works?
I do not believe assigning to theExpected achieves anything.
As expected is final it can be accessed within the anonymous class. If it were used directly in describeTo the object would not be GC'd and the reference would remain valid when the local scope in which expected was declared was left.
Possibly the author of the post you link to believes this explicit style is more readable.
It doesn't matter if theExpected is primitive or Object (though in this example it's an Object), and whether it's mutable or not.
The matches method returns an instance of an anonymous class that extends BaseMatcher (and implements the Matcher interface, assuming that's an interface).
Once it returns the instance, the local variable - expected - that was passed to it is out of scope, but the theExpected member, containing the same value as that local variable, stays within the instance, and can be used by the methods of that instance.
If you want/need to use a local variable in an inner class (in this case, an anonymous local class), the variable must be declared as final regardless if it's primitive or a reference type. This is better explained here: Why Java inner classes require "final" outer instance variables?. Quoting the best explanation IMO:
The reason the language insists on that is that it cheats in order to provide your inner class functions access to the local variables they crave. The runtime makes a copy of the local execution context (and etc. as appropriate), and thus it insists that you make everything final so it can keep things honest.
If it didn't do that, then code that changed the value of a local variable after your object was constructed but before the inner class function runs might be confusing and weird.
In this case, seems like the author want to keep a copy of the parameter sent to the method in the reference of the anonymous class generated for further evaluation. Once the method finishes its execution, the parameter Object expected isn't available anymore, so if you want/need to keep it then you must assign it into a field of your class.
Common design practice is to make instance variables private and have public getters and setters to access them. But many times I have seen code samples on the internet that have constructors that assign values directly to the private instance variable instead of using the setters inside constructors. Am I missing something?
public class Person{
private String name;
public Person(String name){
//is this right, seems like the whole encapsulation purpose is defeated
this.name = name;
//shouldn't this be used
setName(name);
}
public String getName(){
return this.name;
}
public void setName(String name){
this.name = name;
}
}
You are not missing anything. What you do depends entirely on your situation. However, consider this:
It is very common to do parameter validation in a setter. For example, let's say I have a class with field that can hold a value 0 through 10 (the "throws" is unnecessary for the exception type below but I include it for clarity):
public class Example {
private int value;
public Example () {
}
public final int getValue () {
return value;
}
public final void setValue (int value) throws IllegalArgumentException {
if (value < 0 || value > 10)
throw new IllegalArgumentException("Value is out of range.");
}
}
Here, setValue() validates 'value' to make sure it sticks to the rules. We have an invariant that states "an Example will not exist with an out of range value". Now let's say we want to make a constructor that takes a value. You might do this:
public class Example {
...
public Example (int value) {
this.value = value;
}
...
}
As you can see, there is a problem. The statement new Example(11) would succeed, and now an Example exists that breaks our rules. However, if we use the setter in the constructor, we can conveniently add all parameter validation to the constructor as well:
public class Example {
...
public Example (int value) throws IllegalArgumentException {
setValue(value); // throws if out of range
}
...
}
So there are many benefits to this.
Now, there are still cases when you might want to assign values directly. For one, maybe you don't have setters available (although I would argue that creating private or package private setters is still desirable, for the reasons mentioned above, for reflection/bean support if necessary, and for ease of validation in more complex code).
Another reason might be that perhaps you have a constructor that knows, somehow, ahead of time that valid values will be assigned, and therefore doesn't need validation and can assign variables directly. This is usually not a compelling reason to skip using setters though.
However, all-in-all, it's generally a good idea to use the setters everywhere when possible, it will usually lead to cleaner and clearer code that is easier to maintain as complexity increases.
Most of the examples you see where people set variables directly are just people being "lazy" - which is perfectly acceptable if the situation warrants it (perhaps you're writing a quick test program or application and don't want to implement a bunch of setters, for example). There's nothing wrong with that as long as you keep the big picture in mind and only be "lazy" when it's appropriate.
Something I'd like to add based on some of the other answers here: If you override a setter in a subclass, and the data you are setting breaks invariants that the base class assumes, then either the relevant setters should be made final or the base class should not make those assumptions. If overriding setters breaks base class invariants then there is a bigger issue at hand.
You'll notice the getter/setter is final in the above example. This is because our rule is that "any Example must have a value from 0 to 10". This rule therefore extends to subclasses. If we did not have that rule and if an Example could take on any value, then we would not need a final setter and could allow subclasses to override.
Hope that helps.
Sometimes when you would want make the class immutable, it is just one of the things you need to do. And don't have setter methods at all in that case.
Depending on the context, the use of getters and setters is actually a bigger violation of encapsulation than using member variables in constructors. If you want to set the member variable 'name' of this class, either of these approaches would work since the construction is hidden from the caller and thus not violating encapsulation. One warning is that the use of setName within the constructor might call an overrided method in a subclass which may not be what you want (since it may leave name undefined in the superclass).
Here's a similar question to yours that may provide additional insight:
calling setters from a constructor
the private variables are accessible directly anywhere in the class
settng variabels private is to encapsulate them from other classes
Setting variables to private is to encourage encapsulation from other classes.
Unless setName(String) was meant to do something extra (which the method name doesn't imply), it's unnecessary to use the setter while you're in the class where the private variable is.
This does not defeat encapsulation since the private member is still hidden from the other classes
If the modifier method does not contain any logic and just sets the member then there is no difference between directly setting the member of calling its setter method although for better practice the setter should be called.
The setter indicates that this person's name might change in the future and allows it easily without creating an entire person object again.
Initializing variables inside constructor is a very common practice. It can be used to assign values to variables based on which constructor user has called. You cannot write code based on assumption that the client code will invoke setter method to assign value to instance variables. It is always safe to assign default value to a variable when its object is created (i.e inside constructor).
There is a difference between initializing variables within constructor and setting it to different value as per requirement of the calling code(using setter method). Both have different purposes and different objectives.
This is perfectly normal. Some variables might need to be initialized as soon as the object is created, hence it makes sense to pass them in the constructor and many times we may not want to provide setters for those variables to avoid changing the values after object is created.
Its ok to directly assign values with in class provided setter doesn't do any other processing.
Basically setters/getters are used to provide restrictive access to private data such as returning copy of the data instead of reference of private object, validating data in getter etc..
Since the constructor is part of the object itself, and we are sure what we are doing is right, then its ok.
My preferred approach (as described by Joshua Bloch in "Effective Java") is to make the constructor private, make the fields final (i.e., eliminate the setters entirely), and require clients to obtain instances either using the Builder Pattern or Factory Method Pattern, which would take care of any necessary validation to protect invariants. Then the (private) constructor would simply directly assign the given parameters (which have already been validated by the Builder or Factory Method) to the appropriate fields, which are private and final.
I am having a problem with trying to keep my coding organized and as simple as possible. I basically have an array of similar objects that hold multiple values. I am wanting to access those individual values and be able to modify them at will but cannot seem to acess them. This is what the code basically looks like...
//In file Champion.java
package Champions;
public interface Champion{}
//In another file ChoGath.java
package Champions;
public class ChoGath implements Champion{
public static double health = 440.0;
}
//Yet another file Ahri.java
package Champions;
public class Ahri implements Champion{
public static double health = 380.0;
}
//In the main build file LOLChampBuilder.java
package LOLChampBuilder;
import Champions.*;
public class LOLChampBuilder{
public static Champion[] listOfChampions = {new ChoGath(), new Ahri()};
public static void main(String args[]){
//This next line works
System.out.println(new ChoGath().health);
//This next line does not work
System.out.println(listOfChampions[0].health);
}
}
There are more variables and whatnot but this is the basic problem.
ChoGath and Ahri are part of the group Champions and each has their own unique value for health. I want to be able to combine it all into an array for ease of grabbing values because I know where ChoGath (as an example) is in the array.
I get the error Cannot find symbol 'health' in Champions.Champion. I have gone and created the value in Champion and that fixes it (and also change it to class and then extends instead of implements) but then when I go to print the value is always 380.0 as it was the most recent edit to the value health in Champion.
I want it so that I can group all the "Champions" together under a single array (so they need to be the same object type ie: Champion, correct me if I'm wrong) and access their individual values. I cannot seem to do this so I don't know if I need to use ArrayList (which I've never used) or something else entirely. Now I know I could fix this and put it all into a massive file but I am trying to use multiple files for organizational purposes as well as cleanliness. Thoughts on what to do?
You need to add getHealth() to your interface. That's what getters are for.
Also avoid the use of static variables. They tend to produce programming errors.
You have to use getters and setters in the interface to get this functionality, or use a base class instead of an interface for Champion, e.g.:
interface Champion
{
public int getHealth();
public void setHealth(int health);
}
You need to have health variable in your interface. That is similar to concept of Subclass and Superclass. You can't access the variables of subclass using a superclass type because all superclass are not subclass(vice versa is true).You can only access them if its defined in the superclass. If you use a health variable in interface it has to be final static. So its better you use a setter and getter method in the interface to get the value.
interface Champion { public int getHealth(); }
Now implement this method in the ChoGath and Ahri classes