With java you can do :
Integer i = 2;
Is it possible to make such "constructor " instantiation + initialization for my own classes ?
That's not a constructor, that is an example of autoboxing. The short answer is no. The longer answer is yes, if you're willing to write and run a precompiler (or preprocessor) for your project.
This is not actually a constructor. What this is doing is assigning the int literal 2 to an Integer variable.
Just like assigning the return value of a function to a superclass variable.
i.e. Person p = getEmployee(7);
If I understand what you are saying, you want constructors with default values.
Below is an example:
public class MyClass {
private int i;
public MyClass() {
this(2);
}
public MyClass(Integer i) {
this.i = i;
}
}
Related
Preface
I'd like to saying two things:
I don't know how to phrase this question in a few words. So I can't find what I'm looking for when searching (on stackoverflow). Essentially, I apologize if this is a duplicate.
I've only been programming Java consistently for a month or so. So I apologize if I asked an obvious question.
Question
I would like to have a method with a parameter that holds (path to) an integer.
How is such a method implemented in Java code?
Restrictions
The parameter should be generic.
So, when there are multiple of that integer variables, the correct one can be used as argument to the method, when it is called (at runtime).
My Idea as Pseudo-Code
Here's the idea of what I want (in pseudo-code). The idea basically consist of 3 parts:
the method with parameter
the variables holding integer values
the calls of the method with concrete values
(A) Method
.
Following is the definition of my method named hey with generic parameter named pathToAnyInteger of type genericPathToInt:
class main {
method hey(genericPathToInt pathToAnyInteger) {
System.out.println(pathToAnyInteger);
}
}
(B) Multiple Integer Variables
Following are the multiple integer variables (e.g. A and B; each holding an integer):
class A {
myInt = 2;
}
class B {
myInt = 8;
}
(C) Method-calls at runtime
Following is my main-method that gets executed when the program runs. So at runtime the (1) previously defined method hey is called using (2) each of the variables that are holding the different integer values:
class declare {
main() {
hey("hey " + A.myInt);
hey("hey " + B.myInt);
}
}
Expected output
//output
hey 2
hey 8
Personal Remark
Again, sorry if this is a duplicate, and sorry if this is a stupid question. If you need further clarification, I'd be willing to help. Any help is appreciated. And hey, if you're going to be unkind (mostly insults, but implied tone too) in your answer, don't answer, even if you have the solution. Your help isn't wanted. Thanks! :)
Java (since Java 8) contains elements of functional programing which allows for something similiar to what you are looking for. Your hey method could look like this:
void hey(Supplier<Integer> integerSupplier) {
System.out.printl("Hey" + integerSupplier.get());
}
This method declares a parameter that can be "a method call that will return an Integer".
You can call this method and pass it a so called lambda expression, like this:
hey(() -> myObject.getInt());
Or, in some cases, you can use a so called method referrence like :
Hey(myObject::getInt)
In this case both would mean "call the hey method and when it needs an integer, call getInt to retrieve it". The lambda expression would also allow you to reference a field directly, but having fields exposed is considered a bad practise.
If i understood your question correctly, you need to use inheritance to achive what you are looking for.
let's start with creating a hierarchy:
class SuperInteger {
int val;
//additional attributes that you would need.
public SuperInteger(int val) {
this.val = val;
}
public void printValue() {
System.out.println("The Value is :"+this.value);
}
}
class SubIntA extends SuperInteger {
//this inherits "val" and you can add additional unique attributes/behavior to it
public SubIntA(int val) {
super(val);
}
#override
public void printValue() {
System.out.println("A Value is :"+this.value);
}
}
class SubIntB extends SuperInteger {
//this inherits "val" and you can add additional unique attributes/behavior to it
public SubIntB(int val) {
super(val);
}
#override
public void printValue() {
System.out.println("B Value is :"+this.value);
}
}
Now you method Signature can be accepting and parameter of type SuperInteger and while calling the method, you can be passing SubIntA/SuperInteger/SubIntB because Java Implicitly Upcasts for you.
so:
public void testMethod(SuperInteger abc) {
a.val = 3;
a.printValue();
}
can be called from main using:
public static void main(String args[]){
testMethod(new SubIntA(0));
testMethod(new SubIntB(1));
testMethod(new SuperInteger(2));
}
getting an Output like:
A Value is :3
B Value is :3
The Value is :3
Integers in Java are primitive types, which are passed by value. So you don't really pass the "path" to the integer, you pass the actual value. Objects, on the other hand, are passed by reference.
Your pseudo-code would work in Java with a few modifications. The code assumes all classes are in the same package, otherwise you would need to make everything public (or another access modifier depending on the use case).
// First letter of a class name should be uppercase
class MainClass {
// the method takes one parameter of type integer, who we will call inputInteger
// (method-scoped only)
static void hey(int inputInteger) {
System.out.println("hey " + inputInteger);
}
}
class A {
// instance variable
int myInt = 2;
}
class B {
// instance variable
int myInt = 8;
}
class Declare {
public static void main() {
// Instantiate instances of A and B classes
A aObject = new A();
B bObject = new B();
// call the static method
MainClass.hey(aObject.myInt);
MainClass.hey(bObject.myInt);
}
}
//output
hey 2
hey 8
This code first defines the class MainClass, which contains your method hey. I made the method static in order to be able to just call it as MainClass.hey(). If it was not static, you would need to instantiate a MainClass object in the Declare class and then call the method on that object. For example:
...
MainClass mainClassObject = new MainClass();
mainClassObject.hey(aObject.myInt);
...
I have experience working in Java but have recently started doing work in C++, I'm having a little trouble understanding how things are stored in memory in the latter. In java, the following is valid:
class Class {
int myInt;
public Class(int myInt) {
this.myInt = myInt;
}
}
So I have an integer within the class, I give it a value when the object is created. I want to replicate this in C++:
class Class {
int myInt;
public:
Class (int myInt) {
// What goes here?
}
};
This however doesn't work. If I name the variable being passed into the constructor something other than myInt, I can simply state myInt = differentName. But suppose like in the Java, I want both the variable passed to the constructor and the name of the variable to be the same? How can I achieve this?
Two options:
Using an Initializer list:
class Class {
int myInt;
public:
Class (int myInt) : myInt(myInt)
{
}
};
What you were intentionally looking for:
class Class {
int myInt;
public:
Class (int myInt)
{
Class::myInt = myInt;
}
};
But the first one is preferred.
You just need to use the constructor initialization list:
class Class {
int myInt;
public:
Class (int myInt) : myInt(myInt)
{
// by the time you get here, myInt is already initialized.
// You can assign a value to it or modify it otherwise,
// but you cannot initialize something more than once.
}
};
That the only way to explicitly initialize a data member in a constructor. Once you're in the body of the constructor, all data members have been initialized.
In addition to the initializer syntax, this is also available in C++. You would use it as this->myInt because this is a pointer.
"this" is a pointer in C++. So it'll be
this->myInt = myInt;
The following is the way to achieve the same in c++
this->myInt = myInt;
I'd simply like to know if the following is possible to do somehow.
public void foo(int a) {
String a = Integer.toString(a);
}
Now obviously this code doesn't actually work; the string a shadows the parameter a. What I'd like to know is, is there a way to explicitly tell the compiler "Hey, this is actually that other a up there!" I'm looking for something similar to the this keyword, except for method parameters.
Is there anything like this or am I forced to use a different variable name?
No, this feature does not exist in java. You should just make up another variable name.
You can do-
String ab = Integer.toString(a);
Even if you could use the same variable name as the parameter variable, it would create confusion. You cannot do that in Java. Just use some other variable name.
Also, modifying method parameters are not a good idea. Rather, have them declared final like-
public void foo(final int a) {
String ab = Integer.toString(a);
}
You can't do that but you could overload the method
public void foo(int a) {
foo(Integer.toString(a));
}
public void foo(String a) {
//
}
For what you want to do, you should probably just create another variable. For example:
public void foo(int a1) {
String a = Integer.toString(a1);
}
You cannot have twice the same name of the variable in the same range. But you can override names of the variables, fields for example:
class A
{
int a;
void f(int a)
{
this.a = a;
}
}
Now field a is overridden, and using this you can refer to the overriden field.
I have a class with several methods. Now I would like to define a helper method that should be only visible to method A, like good old "sub-functions" .
public class MyClass {
public methodA() {
int visibleVariable=10;
int result;
//here somehow declare the helperMethod which can access the visibleVariable and just
//adds the passed in parameter
result = helperMethod(1);
result = helperMethod(2);
}
}
The helperMethod is only used by MethodA and should access MethodA's declared variables - avoiding passing in explicitly many parameters which are already declared within methodA.
Is that possible?
EDIT:
The helper mehod is just used to avoid repeating some 20 lines of code which differ in only 1 place. And this 1 place could easily be parameterized while all the other variables in methodA remain unchanged in these 2 cases
Well you could declare a local class and put the method in there:
public class Test {
public static void main(String[] args) {
final int x = 10;
class Local {
int addToX(int value) {
return x + value;
}
}
Local local = new Local();
int result1 = local.addToX(1);
int result2 = local.addToX(2);
System.out.println(result1);
System.out.println(result2);
}
}
But that would be a very unusual code. Usually this suggests that you need to take a step back and look at your design again. Do you actually have a different type that you should be creating?
(If another type (or interface) already provided the right signature, you could use an anonymous inner class instead. That wouldn't be much better...)
Given the variables you declare at the top of your method can be marked as final (meaning they don't change after being initialized) You can define your helper method inside a helper class like below. All the variables at the top could be passed via the constructor.
public class HelperClass() {
private final int value1;
private final int value2;
public HelperClass(int value1, int value2) {
this.value1 = value1;
this.value2 = value2;
}
public int helperMethod(int valuex) {
int result = -1;
// do calculation
return result;
}
}
you can create an instance of HelperClass and use it inside the method
It is not possible. It is also not good design. Violating the rules of variable scope is a sure-fire way to make your code buggy, unreadable and unreliable. If you really have so many related variables, consider putting them into their own class and giving a method to that class.
If what you mean is more akin to a lambda expression, then no, this is not possible in Java at this time (but hopefully in Java 8).
No, it is not possible.
I would advise you create a private method in your class that does the work. As you are author of the code, you are in control of which other methods access the private method. Moreover, private methods will not be accessible from the outside.
In my experience, methods should not declare a load of variables. If they do, there is a good chance that your design is flawed. Think about constants and if you couldn't declare some of those as private final variables in your class. Alternatively, thinking OO, you could be missing an object to carry those variables and offer you some functionality related to the processing of those variables.
methodA() is not a method, it's missing a return type.
You can't access variables declared in a method from another method directly.
You either has to pass them as arguments or declare methodA in its own class together with the helpermethods.
This is probably the best way to do it:
public class MyClass {
public void methodA() {
int visibleVariable=10;
int result;
result = helperMethod(1, visibleVariable);
result = helperMethod(2, visibleVariable);
}
public int helperMethod(int index, int visibleVariable) {
// do something with visibleVariable
return 0;
}
}
I'm learning to do some Java 101 syntax stuff. In an exercise I'm trying to do, I can't get the incremented value to print. Any ideas?
Here is my code:
class StaticTest {
static int i = 47;
}
class incrementable {
static void increment() { StaticTest.i++; }
}
class DataOnly {
int i;
double d;
boolean b;
public static void main (String[] args) {
incrementable t = new incrementable();
DataOnly df = new DataOnly();
df.i = t.increment();
System.out.println(df.i);
}
}
The error I get is:
aTyp0eName.java:18: incompatible types
found: void
required: int
df.i = t.increment();
df.i is an int and so is t.increment. I'm guessing it's because increment() is void?
your method signature is:
static void
Which means nothing is returned from this method.
Hence, attempting to assign increment() to df.i won't work.
increment() doesn't have a return value. You'd need to have it return an int for your code to work:
class incrementable {
static int increment() {
StaticTest.i++;
return StaticTest.i;
}
}
"void" is a keyword reserved for methods which don't return any value. Otherwise, you specify what class or primitive you return (int, double, String, whatever). You can read more about return values here.
Also, for future reference, class names should be capitalized, so you should be using "Incrementable" rather than "incrementable". (In my sample code I kept it the same as you had it so you could just drop the code in for now.)
The error I get is:
aTyp0eName.java:18: incompatible types
found: void
required: int
df.i = t.increment();
df.i is an int and so is t.increment [fault?]. I'm guessing it's because increment() is void?
Eeeexactly, your guess is correct.
This is the error message explained line by line:
aTyp0eName.java:18: incompatible types
You are trying to assign "void" to an int in line 18.
df.i = t.increment();
Here is where the error is.
found: void
You declare what's the return type in the method "signature".
The method signature is :
<access modifiers> <return type> <method name> (<parameters> )
static void increment ()
So the return type is void.
Next line:
required: int
df.i is int as you have previously stated.
So, pretty much you have already your own question answered.
The good point of having a compiler is that it tells you when something is wrong.
The bad thing ( for humans ) you have to learn to read those messages. They vary from programming language to another and even from compiler to compiler.
This would be a corrected version:
class StaticTest {
static int i = 47;
}
class Incrementable {
static int increment() {
return ++StaticTest.i;
}
}
class DataOnly {
int i;
double d;
boolean b;
public static void main (String[] args) {
Incrementable t = new Incrementable();
DataOnly df = new DataOnly();
df.i = t.increment();
System.out.println(df.i);
}
}
There are some other enhancements could be done, such as adding access modifiers to the methods and attributes, but for now I think this would help.
The answer is that the increment() method returns a void. That being said, there are a lot of violations of the Java standard syntax that programmers generally use, Namely:
Class names should start with a capital letter.
fields should not be mutated from different classes, rather a helper method should be within the same class
If you want to call a static method, don't reference an instance variable, rather use ClassName.reference
If a variable is only needed locally, it should not be a field (df.i could just be an int i declared within the main method).
EDIT:
An example of a helper method within the same class:
class StaticTest {
private static int i = 47; //keep i private and mutate and access via methods
public static void increment() { i++; }
public static int getI() { return i; }
}
also, if you instantiate incrementable, you shouldn't define the method increment() as static. or you can, but don't need to.
you could simply incrementable.increment() if it's static.
just a tip. as for the answer to your question, toolkit already said that right.
Also, your incrementable class should really be Incrementable.