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.
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);
...
Okay, I'm a newbie and I need some advice about organization in my code. I've been getting an error that says my arraylist cannot resolved.
What I'm doing is I'm extending an abstract class (I don't know if thats relevant) and I've created an array list in my main and filled it with things and then I've got my method to print out the contents of that array list.
If anyone can help me, please do. Thanks
Here's my code:
public static void main(String[] args) {
ArrayList <String> Strings = new ArrayList <String>();
Strings.add("Hi");
Strings.add("How are you");
Strings.add("Huh");
}
public void showFirstString(){
for (int i = 0; i < Strings.size(); i++){
System.out.println(Strings(i));
}
}
Please avoid using the word String as a variable name because java already used it as a keyword. Just replace it with another name.
Here is what you should do because you are using ArrayList:
public static void main(String[] args) {
ArrayList <String> list= new ArrayList <String>();
list.add("Hi");
list.add("How are you");
list.add("Huh");
showFirstString(list);
}
public static void showFirstString(ArrayList list){
for (int i = 0; i < list.size(); i++){
System.out.println(list.get(i));
}
}
And make sure to import the ArrayList library.
read more about its docu here
You need to use the .get(index) method, where index is the element you want to access. For example:
System.out.println(Strings.get(i));
You would also want to call that method in main.
You never call showFirstString() and in addition, Strings isn't a global variable, so you will get an error on the first line of that method. To fix this, put showFirstString(Strings) in your main method and change your method signature to public void showFirstString(Arraylist Strings). In addition, arraylists are accessed using list.get(index) so change the line in your loop to System.out.println(Strings.get(i));
If you want to get elements from an array list, you have to use list.get(index) method as follows. It's because you cannot access elements as in arrays when it comes to array lists.
public void showFirstString(){
for (int i = 0; i < Strings.size(); i++){
System.out.println(Strings.get(i));
}
}
First of all, your naming convention is not very good.
Second,List collection circular elements is list.get(index),is not list(index)
There are answers that address what OP should do to improve but I feel the important part in his question my arraylist cannot resolved. is not discussed. My answer adds to that part.
When compilers complain XXX cannot be resolved, it means that the compiler is encountering the variable's name for the first time and has no idea of what the stuff with that name is. In your case, the compiler does not know what is Strings in showFirstString(), and because it does not know what is Strings, it stops compiling and complains to you instead of keep going with knowing nothing about it, which could potentially be dangerous.
The reason the compiler could not know what was Strings in showFirstString() is known as the scope of variables. Basically, there are lots of blocks in Java as in:
public void myMethod()
{ /* method body block is here* }
or even like,
public class myClass
{
/* here starts the class body */
public static void myMethod()
{ /* method body block is here* }
}
And the thing is that the variables are known only within a block where it's declared. So for example, if your codes looks like this:
public class myClass
{
int foo; // it is known to everywhere within this class block
public static void myMethod()
{
// boo is known only within this method
int boo = foo + 1; // fine, it knows what foo is
}
public static void myMethod2()
{
// bar is known only within this method
int bar = boo + 1; // cause errors: it does not know what boo is
}
}
Now you should understand why your programme was not able to know what is Strings. But passing around data within your codes is a common stuff that is often required to do. To achieve this, we pass parameters to methods. A parameter is a data specified within () that follows the name of the method.
For example:
public class myClass
{
int foo; // it is known to everywhere within this class block
public static void myMethod()
{
// boo is known only within this method
int boo = foo + 1; // fine, it knows what foo is
myMethod2(boo); // value of boo is passed to myMethod2
}
public static void myMethod2(int k) // value of k will be boo
{
// bar is known only within this method
int bar = k + 1; // cause errors: it does not know what boo is
}
}
With parameters like above, you can use boo in myMethod2(). The final thing is that with the codes above, your codes will compile but will do nothing when you run it, because you did not start any of the methods. When a programme runs, it looks for the main method and any other methods that you want to invoke should be called in methods, or by other methods that are in main.
public class myClass
{
int foo; // it is known to everywhere within this class block
public static void main(String[] args)
{
// start myMethod
myMethod();
}
public static void myMethod()
{
// boo is known only within this method
int boo = foo + 1; // fine, it knows what foo is
myMethod2(boo); // value of boo is passed to myMethod2
}
public static void myMethod2(int k) // value of k will be boo
{
// bar is known only within this method
int bar = k + 1; // cause errors: it does not know what boo is
}
}
I hope you get the idea. Also note that to get the items in an ArrayList, you need to use ArrayList.get(int index), as others noted.
First of all, as others have pointed out, you will need to use the Strings.get(i) method to access the value stored inside a given list element.
Secondly, as Matthias explains, the variable Strings is out of scope and therefore cannot be accessed from the showFirstString() method.
Beyond that, the problem is that your main() method, which is static, cannot interact with the instance method showFirstString() and vice versa.
Static methods live at the class level and do not require an instance of that class to be created. For example:
String.valueOf(1);
Instance methods on the other hand, as the name implies, require an instance of that class to be created before they can be called. In other words, they are called on the object (instance of the class) rather than the class itself.
String greeting = "hi there";
greeting.toUpperCase();
This provides further details:
Java: when to use static methods
Without knowing your specific situation, you have two options...
Make both your Strings list as static (class level) field and showFirstString() method static.
public class ListPrinterApp {
static ArrayList<String> Strings = new ArrayList <String>();
public static void main(String[] args) {
Strings.add("Hi");
Strings.add("How are you");
Strings.add("Huh");
showFirstString();
}
static void showFirstString(){
for (int i = 0; i < Strings.size(); i++){
System.out.println(Strings.get(i));
}
}
}
Move code that deals with the list into a separate class, which is then called from your application's static main method. This is likely a better option.
public class ListPrinter {
ArrayList<String> Strings = new ArrayList<String>();
public ListPrinter() {
Strings.add("Hi");
Strings.add("How are you");
Strings.add("Huh");
}
public void showFirstString() {
for (int i = 0; i < Strings.size(); i++) {
System.out.println(Strings.get(i));
}
}
}
public class ListPrinterApp {
public static void main(String[] args) {
ListPrinter printer = new ListPrinter();
printer.showFirstString();
}
}
(I put the the Strings.add() calls into the constructor of ListPrinter as an example. Presumably, you would not want to hardcode those values, in which case you should add an add() method to your ListPrinter class through which you can populate the list.)
A few additional points not directly related to your question:
Take a look at the naming conventions for variables in Java. Specifically:
If the name you choose consists of only one word, spell that word in
all lowercase letters. If it consists of more than one word,
capitalize the first letter of each subsequent word.
Consider using the interface List instead of the concrete implementation of ArrayList when declaring your variable (left side of the equals sign). More info here.
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.
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.