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);
...
Related
In Java 8 I want to create something that returns an argument or creates an instance if the argument is null.
I could do this by creating a static method or a UnaryOperator. Are the following approaches technically the same or are there technical differences that I should be aware of with either approach:
Static Method
static Cat initOrReturn(Cat c) {
if (c==null) {
return new Cat();
}
return c;
}
Function
UnaryOperator<Cat> initOrReturn = c -> {
if (c==null) {
return new Cat();
}
return c;
}
First your code has syntax error, in the second block first line between c and { there should be a ->.
The second one creates an anonynous object, the first one only creates a static method.
So they're not the same.
Also, static methods can be used in stream API.
If you have:
class A {
static Object a(Object x) { return x; /* replace with your code */ }
}
You can:
xxxList().stream().map(A::a)
Creating a method is often considered dirty, because it's globally visible.
It's recommended to use lambda expressions without declaring a variable.
You can think about function as a "value" - something that can be stored to variable, and passed around.
This "value" can be used as e.g. method parameter to (during runtime) dynamically change part of method implementation.
Take a look at this basic example. Hope that can illustrate idea:
static Number functionsUsageExample(Integer someValue, UnaryOperator<Number> unaryOperator) {
if (someValue == 1) {
//do something
}
Number result = unaryOperator.apply(someValue); // dynamically apply supplied implementation
// do something else
return result;
}
public static void main(String[] args) {
UnaryOperator<Number> add = i -> i.doubleValue() + 20;
UnaryOperator<Number> multiply = i -> i.intValue() * 3;
var additionResult = functionsUsageExample(1, add);
var multiplicationResult = functionsUsageExample(1, multiply);
//additionResult value is: 21.0
//multiplicationResult value is: 3
}
Function can be also used as a 'helper methods' stored inside method block. This way you will not corrupt class scope with method that is used only in one place.
I'm trying to generalise some code by iterating over all constants of an enum to receive the same specific argument from each one.
Specifically I have an enum P with some constants A,B,C.
Each of these constants is itself an enum and implements an interface I that defines a function f.
P.values() gives me an array P[] A = {A,B,C}, however I can't call A[i].f() since A[i] is of course of type P which doesn't implement I.
Now in my understanding a function can return an interface, but I can not instantiate it and therefore can't cast to it.
Should I overwrite values() for P to return I[]? If so, how would I do that since I can't cast to I? Or is there another solution?
I am working in eclipse but assuming that it's complaints are indicative of a true mistake, not just eclipse not recognising types.
Since I'm somewhat new to Java I would also appreciate any links to resources that explain the underlying rules of type matching/checking.
This seems to do what you describe - perhaps I have misunderstood your question though. If so please explain further.
interface I {
void f ();
}
enum P implements I{
A,
B,
C {
// Demonstrate enum-specific implementation.
#Override
public void f () {
System.out.println("SEEEEEE!");
}
};
// By default `f` prints the name of the enum.
#Override
public void f () {
System.out.println(name());
}
}
public void test() throws Exception {
for ( I i : P.values()) {
i.f();
}
}
I was wondering if it's possible to call another function just by adding the function name to the parameter. So for instance I want to make a script with 4 parts. Each part requires input (I am using a scanner, dont ask why :P its the assignment) and then needs to pass it to another script for e.g. calculations and stuff.
I start of with this:
static int intKiezer(String returnFunctie, String text) {
Scanner vrager = new Scanner(System.in);
while (true) {
System.out.println(text);
int intGekozen = vrager.nextInt();
if (vrager.hasNextInt()) {
returnFunctie(intGekozen);
}
else {
vrager.next();
System.out.println("Verkeerde invoer!");
}
}
As you see I am trying to push the obtained value to another function by trying to call it (returnFunctie(intgekozen)). It should be calling returnFunctie with intgekozen as parameter. But its not working
I would be calling the function like this: intKiezer(sphereCalculations, "What radius do you want to have?"). So the answer from the input, if its correct should be passed to another function called sphereCalculations
Here is an idea.
Define an interface that has a method that does whatever calculation you want to perform. For example:
interface Algorithm {
int execute(int value);
}
Then define one or more classes that implement the interface and do whatever calculations you want them to do. For example:
class MultiplyByTwo implements Algorithm {
public int execute(int value) {
return value * 2;
}
}
class AddThree implements Algorithm {
public int execute(int value) {
return value + 3;
}
}
Then, write your method so that it accepts an Algorithm as a parameter. Execute the algorithm with the desired value.
static int intKiezer(Algorithm algo, String text) {
// ...
return algo.execute(intGekozen);
}
Call your method by passing in an instance of one of the implementation classes of interface Algorithm.
int result = intKiezer(new MultiplyByTwo(), "Some question");
System.out.println("Result: " + result);
As #Jesper said, it is possible with reflection, and probably only with reflection. Reflection is the process in which an object can analyze itself and iterate through it's members (attributes and methods). In your case, it seems you are looking for a method.
By the looks of your code, it seems like what you want is, in fact, passing a function object to your code, where a parameter could be applied. This isn't possible in Java. Something similar will be possible in Java 8 with the addition of closures. You could do that in Groovy, by passing a Closure as a parameter, or other language with support for closure or functions.
You can get near what you want by defining an abstract class/interface, passing an instance of it to your method, and then calling a method passing the parameter to it, like:
interface Function <T> {
public Integer call(T t);
}
public class TestFunction {
static int intKiezer(Function<Integer> returnFunctie, String text)
{
int a = 10;
System.out.println(text);
return returnFunctie.call(a);
}
public static void main(String[] args)
{
Function<Integer> function = new Function<Integer>() {
public Integer call(Integer t) { return t * 2; }
};
System.out.println( intKiezer(function, "Applying 10 on function") );
}
}
If your intention is to call a method, then you are better using some reflection library. Apache Common's MethodUtil comes to mind. I think this your man:
invokeMethod(Object object, String methodName, Object arg)
Invoke a named method whose parameter type matches the object type.
Can someone tell me what is the need to declare a class like this:
public class Test {
String k;
public Test(String a, String b, String c){
k = a + " " + b + " " + c; //do something
}
public void run(){
System.out.println(k);
}
public static void main(String[] args) {
String l = args[0];
String m = args[1];
String n = args[2];
Test obj = new Test(l,m,n);
obj.run();
}
}
Of course it works but I don't get the point why would one use such way to implement something. Is it because we need to pass arguments directly to the class main method that is why we use this way or is there some other reason?
What is the purpose of public Test(...) using the same class name. Why is it like this?
The public Test(...) is a constructor and its purpose is for object creation. This is clearly seen from the sample code...
Test obj = new Test(l,m,n);
The variable obj is instantiated with object Test by being assigned to the Test's constructor. In java, every constructor must have the exact same name (and case) as the java file it's written in (In your case constructor Test is found in Test.java).
...Why is it like this?
It all depends on what you want to do with your object. You could have a zero-argument constructor (i.e. requires no parameters) and have methods to set your l, m, n, like so:
package net;
public class Test {
private String k;
/**
*
*/
public Test() {
super();
// TODO Auto-generated constructor stub
}
public void set(String a, String b, String c) {
k = a + " " + b + " " + c; //do something
}
public void run() {
System.out.println(k);
}
public static void main(String[] args) {
String l = args[0];
String m = args[1];
String n = args[2];
Test obj = new Test();
obj.set(l, m, n);
obj.run();
}
}
As you can see, it's exactly the same feature as your example but with a zero-argument constructor.
If your class has no constructor at all, java adds a public zero-argument constructor for you automatically.
Hope this helps.
The method called Test is a so-called constructor for the Test class. The constructor is the method that gets called when you write something like new Test(...).
Bear in mind that the main method is a static method, which means that it does not require an instance of the class Test to be called. This is not the case for the run method. run is an instance method, and to invoke it you need an instance of the Test class (the obj in your case).
The public Test(...) bit is the constructor of that class. It always has the same name as the class. Classes and main methods are two quite different aspects of programming. Classes define reusable components that have both state and methods. The main method is a special method that gets called from the command line.
Your example is so trivial that it doesnt really show any benefits of Object Orientated Programming. If you consider an example where you had different Classes intetracting you might get more of a feel for it.
The main method is the entry point for the program and is called when you run java Test from the command line.
public Test(String a, String b, String c) is a public constructor for the Test class and is called when you call new Test(l,m,n); Note that a in the constructor and l in main method refer to the same String... this also applies to b and m; c and n.
As a side note, this class expects to be passed three values from the command line, and then stores them in l, m, and n
One last note: If you have a method with the signature public void run(), your class should likely implement Runnable so that it can be used in a Thread.
Learn Java.
A constructor is a function that gets called to create an object, and it's denoted by a function with the same name as the class, but no return type. Multiple constructors can be declared with different arguments.
In this case, the arguments are taken out of the argument array and passed as arguments to the constructor for Test.
These are fundamentally basic concepts to the Java programming language. You should read up on Java. Try Thinking in Java, this is a great book to get started.
Consider this:
class A {
int x =5;
}
class B extends A{
int x =6;
}
public class CovariantTest {
public A getObject() {
return new A();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
CovariantTest c1 = new SubCovariantTest();
System.out.println(c1.getObject().x);
}
}
class SubCovariantTest extends CovariantTest {
public B getObject(){
return new B();
}
}
As far as I know, the JVM chooses a method based on the true type of its object. Here the true type is SubCovariantTest, which has defined an overriding method getObject.
The program prints 5, instead of 6. Why?
The method is indeed chosen by the runtime type of the object. What is not chosen by the runtime type is the integer field x. Two copies of x exist for the B object, one for A.x and one for B.x. You are statically choosing the field from A class, as the compile-time type of the object returned by getObject is A. This fact can be verified by adding a method to A and B:
class A {
public String print() {
return "A";
}
}
class B extends A {
public String print() {
return "B";
}
}
and changing the test expression to:
System.out.println(c1.getObject().print());
Unless I'm mistaken, methods are virtual in java by default, so you're overriding the method properly. Fields however (like 'x') are not virtual and can't be overriden. When you declare "int x" in B, you are actually creating a totally new variable.
Polymorphism doesn't go into effect for fields, so when you try and retrieve x on an object casted to type A, you will get 5, if the object is casted to type B, you will get 6.
When fields in super and subclasses have the same names it is referred to as "hiding". Besides the problems mentioned in the question and answer there are other aspects which may give rise to subtle problems:
From http://java.sun.com/docs/books/tutorial/java/IandI/hidevariables.html
Within a class, a field that has the
same name as a field in the superclass
hides the superclass's field, even if
their types are different. Within the
subclass, the field in the superclass
cannot be referenced by its simple
name. Instead, the field must be
accessed through super, which is
covered in the next section. Generally
speaking, we don't recommend hiding
fields as it makes code difficult to
read.
Some compilers will warn against hiding variables