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.
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 two classes
Class1:
public class Class1 {
public static void main(String[] args) {
Class2 classObject = new Class2();
classObject.add(2, 3);
classObject.print();
}
}
And Class2:
public class Class2 {
public int add(int a, int b) {
int n = a + b;
return n;
}
public void print() {
System.out.println(add(2,3));
}
}
I want to use the print method to print out what is being returned in the add method.The add method gets its information from the classObject as seen in Class1.
I know there are different ways to go about doing this, but i'm quite sure that there is a way to do it the way i want to, i just can't figure out how.
In Class2 in the print method when i called the add method i put arbitrary numbers there. What i want to do is somehow bring the numbers from from classObject.add(int,int) and print the the returning integer n.
If what you want to demonstrate is showing an object with state, maybe you mean something like this:
public class Class2 {
int n;
public void add(int a, int b) {
n = a + b;
return n;
}
public void print() {
System.out.println(n);
}
}
This way Object1 never knows the internals of Object2, and it's really a pretty good abstraction.
You can simply change the signature of the print method as below. Method like print are processing methods which needs the input which you can pass as method arguments.
public void print( int a) {
System.out.println(a);
}
Now you need to make a simple call like below.
classObject.print(classObject.add(2,3));
You should not be calling add method from inside the print method. As per the name it seams print is a general purpose method. You should pass input as method arguments and it should be responsible to print the input.
If you wish your print method to just print addition then You can pass the two numbers as input parameters to method print and also change the method name as below. You need to call the method add from inside the print (modified version). In this case you should hide the method add and make it private.
public void printTheAddition(int n, int m){
System.out.println(add(n,m));
}
In this case just call printTheAddition method with two input arguments.
I have created an example class for my problem below.
public class testClass {
public void testMethod()
{
int testInteger = 5;
}
String testString = "Hello World" + testInteger;
}
I have an integer inside a method and a string that is in no method as seen above. I want the string to get the integer that inside the method but it cannot. Can someone please help explain why that is so and tell me how to make the string the integer. thanks.
For example:
public class testClass {
public int testMethod()
{
int testInteger = 5;
return testInteger;
}
String testString = "Hello World" + testMethod();
}
The integer is a variable inside the method; it has scope of the method which means it can't be accessed from outside the method. The String is a field; it has scope of the class, so it can be accessed from anywhere inside the class including inside the method.
It's basic Java... the testInteger is defined in the method so not available out of the method. You could let the method return an int (being your testInteger) and call that method.
You cannot access a local variable from another method without returning it.
public int testMethod()
{
int testInteger = 5;
return testInteger;
}
Then you can get the value by calling the method (assuming you have an instance of your class in a reference instance),
String testString = "Hello World" + instance.testMethod();
From The Java Tutorials: Variables,
Local Variables Similar to how an object stores its state in fields, a method will often store its temporary state in local variables. The syntax for declaring a local variable is similar to declaring a field (for example, int count = 0;). There is no special keyword designating a variable as local; that determination comes entirely from the location in which the variable is declared — which is between the opening and closing braces of a method. As such, local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class.
Lets break down your code to see what is going on
you have such a function
public void testMethod()
{
int testInteger = 5;
}
as you see the return type is void so nothing will be return to anywhere that is called this method.
you have this line after your testMethod
String testString = "Hello World" + testInteger;
first it looks odd why?
because you do not have any main method so I do not know how your code runs
but Imagine you have main method like this
public static void main(String[] args){
String testString = "Hello World" + testInteger;
}
second, you did not even call your testMethod in order to utilize it inside your main method
Issues
1. you did not call your testMethod at all
2. Even if you called it, it would not help you because your return type is void
3. you need main method in order your code to be ran
Remedies
1. change your return type to int
your function signature:
public int testMethod()
2. if you want to use your method, you have to use it in your main method like
for example:
String testString = "Hello World" + testMethod();
3. do not forget to have your main method because it is necessary for your code to be ran
your main method signature is
public static void main(String[] args)
How to initialize the values in constructor that the values cannot be passed by object and that we could pass them from main method?
class ex
{
int a,b;
ex()
{
this.a=b;
}
public static void main(String args[])
{
//here we pass the values to that consructor ex
ex obj=new ex();
}
}
make an overloaded constructor which accepts two arguments.
public ex(int a, int b) {
this.a = a;
this.b = b;
}
public static void main(String...args){
ex obj = new ex(1,2)
}
values canntot be passed by object we should pass from main method
If i understand correctly, you want to pass arguments from the main method and nitialize them in your constructor, the only was to do is by passing them to the constuctor while object creation
You can call setter method from constructor if don't want to display initialization values while declaring new object.
Please see code below for reference :
class Testcl {
int a,b;
Testcl(){
setValues(1,2);
}
private void setValues(int a, int b){
this.a=a;
this.b=b;
}
public static void main(String [] args){
Testcl test = new Testcl();
System.out.println("a : " + test.a + " b : " + test.b);
}}
The first thing to say is that this does actually "work" ... in the sense that it compiles and executes without any errors.
int a,b; // default initialized to 'zero'
ex() {
this.a=b; // assigns 'zsro' to a.
}
But of course, it doesn't achieve anything ... because a is already zero at that point.
Now the main method could assign something to the a and/or b fields after the constructor returns. But there is no way (in pure Java1) to get some non-zero value into b before the constructor is called ... if that is what you are asking.
The practical solution is to just to add a and b arguments to the constructor.
1 - a non-pure Java solution might be to "monkey around" with the bytecodes of the constructor so that it does what you "need" to do. But that's pretty horrible, and horrible solutions have a tendency of coming back to bite you.
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.