I have to create two classes, let's call them A and B .
public class A {
double Number1;
double Number2;
A(double Number1, Number2){
this.Number1=Number1;
this.Number2=Number2;
}
}
Now i have a void main class where someone enter their Number 1 and Number 2
public static void main(String[] args) {
A game=new A(555, 999);
}
Now, i Want to Create another Class Called B, and i want the Numbers 555, and 999 to be transferd/to use the same values into class B
like
public class B{
///double a= 555;
///double c= 777;
}
I need these operators a, and c to fetch data from public static void main class
Can someone explain me how to do this?
Thanks.
One way to do this is to add some get methods into A:
public double getNumber1() {
return Number1;
}
public double getNumber2() {
return Number2;
}
And add set methods into B:
public void setA(double a) {
this.a = a;
}
public void setC(double c) {
this.c = c;
}
Then instantiate B in your main class:
B b = new B();
And set the values then:
b.setA(game.getNumber1());
b.setC(game.getNumber2());
Now the values of a and c of your instance of B are 555 and 999.
Or perhaps:
public B(double a, double c) {
this.a = a;
this.c = c;
}
and pass the values into the constructor:
B b = new B(game.getNumber1(), game.getNumber2());
One basic principal of OOP is that we have certain objects with certain properties build upon classes. These classes 'act as blueprints' for objects which should use their behaviour.
As I mentioned in a comment you could create a constructor who takes an object of class A as a parameter:
public class B
{
private double value1;
private double value2;
public B( A aObject )
{
value1 = aObject.getVal1();
value2 = aObject.getVal2();
}
// rest of the class...
}
with a class A:
public class A
{
private double val1;
private double val2;
public A( double val1, double val2 )
{
this.val1 = val1;
this.val2 = val2;
}
public double getVal1()
{
return val1;
}
public double getVal2()
{
return val2;
}
}
and a main method:
public static void main( String[] args )
{
A aObject = new A( 100, 100 );
B bObject = new B( aObject );
}
Doing so would alow objects of class A to exist on their own but objects of class B always need a 'foundation' in form of another object from which they can copy their values.
Also take a small read on encapsulation
You can extend A class on B. The code bellow will help you out.
public class ClassA {
double number1;
double number2;
public ClassA(double number1, double number2) {
this.number1 = number1;
this.number2 = number2;
}
}
public class ClassB extends ClassA {
public ClassB(double number1, double number2) {
super(number1, number2);
}
public double getNumber1() {
return number1;
}
public double getNumber2() {
return number2;
}
}
If you access the classB.getNumber1() method you will get your results.
You need getter methods in you classes to query the values. In your case for the member variables Number1 and Number2.
Here is an example for you, consider the change of upper-/lowercase names:
public class A {
// value of number 1
// member variables should start lowercase
// they should be private so they are not modified from the outside
private double number1;
// value of number 2
private double number2;
// constructor:
public A(double number1, double number2) {
// in a custom constructor you should
// alwas run the superconstructor at first:
super();
setNumber1(number1);
setNumber2(number2);
}
// setter/getter for number 1:
// search the internet for "camelcase" description
// (lower/upper cases in method/member names)
public void setNumber1(double theNumber) {
this.number1 = theNumber;
}
public void getNumber1() {
return this.number1;
}
// do the same for number 2
}
Now, you can use these getters to retrieve the data. Build class B the same way and you go like this:
public static void main (String[] args) {
A a = new A(555, 666);
B b = new B(a.getNumber1(), a.getNumber2());
}
Useless to say that in this example class A and class B don't differ, so class B is nonsense. But if your classes are going have different signatures (member variables, methods and so an), this is a proper way.
Related
Interface and a class Number1, later Number2, etc.
When I try to use member data inside method add(), it demands that I cast it first to class type.
However if I use member method inside method add(), it does not demand that I cast to class type.
Any explanation will be appreciated.
Code below attached.
package mynums;
//Interface for all my number types, Number1, Number2 (not shown), etc
public interface NumberIF
{
public int getNum();
public void setNum(int numx);
//I will have other types of numbers not just Number1.
//I will have Number2, etc.
public void add(NumberIF f1, NumberIF f2);
public void print();
}
package mynums;
//There will be other types of numbers Number2, Number3
//all doing these operations but different.
//This is just to test the concept.
//But I have a problem here.
public class Number1 implements NumberIF
{
private int num;
public Number1()
{
num = 1;
}
public Number1(int numx)
{
num = numx;
}
public int getNum()
{
return (num);
}
public void setNum(int numx)
{
num = numx;
}
public void add(NumberIF f1, NumberIF f2)
{
int numt;
/**
* Why to use member variables I must specify the type of class.
* Why to use member method I do not have to specify type of class.
*/
//numt = f1.num + f2.num; ERROR
// either one works
//Why accessing member data is different from accessing member method.
numt = ((Number1)f1).num + ((Number1)f2).num;
numt = f1.getNum() + f2.getNum();
num = numt;
}
public void print()
{
System.out.println(num);
}
static public void main(String[] args)
{
Number1 f1, f2, f3;
f1 = new Number1(1);
f2 = new Number1(2);
f3 = new Number1(0);
f3.add(f1, f2); // 1 + 2= 3
f3.print();
}
}
Java is a statically-typed language.
Variables of static type NumberIF do not necessarily point to objects of type Number1, so those objects may not have the field num.
You only get to use the members of the static type (and its supertypes) of the variable.
I am trying to return 2 values from a Java method but I get these errors. Here is my code:
// Method code
public static int something(){
int number1 = 1;
int number2 = 2;
return number1, number2;
}
// Main method code
public static void main(String[] args) {
something();
System.out.println(number1 + number2);
}
Error:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - missing return statement
at assignment.Main.something(Main.java:86)
at assignment.Main.main(Main.java:53)
Java Result: 1
Instead of returning an array that contains the two values or using a generic Pair class, consider creating a class that represents the result that you want to return, and return an instance of that class. Give the class a meaningful name. The benefits of this approach over using an array are type safety and it will make your program much easier to understand.
Note: A generic Pair class, as proposed in some of the other answers here, also gives you type safety, but doesn't convey what the result represents.
Example (which doesn't use really meaningful names):
final class MyResult {
private final int first;
private final int second;
public MyResult(int first, int second) {
this.first = first;
this.second = second;
}
public int getFirst() {
return first;
}
public int getSecond() {
return second;
}
}
// ...
public static MyResult something() {
int number1 = 1;
int number2 = 2;
return new MyResult(number1, number2);
}
public static void main(String[] args) {
MyResult result = something();
System.out.println(result.getFirst() + result.getSecond());
}
Java does not support multi-value returns. Return an array of values.
// Function code
public static int[] something(){
int number1 = 1;
int number2 = 2;
return new int[] {number1, number2};
}
// Main class code
public static void main(String[] args) {
int result[] = something();
System.out.println(result[0] + result[1]);
}
You could implement a generic Pair if you are sure that you just need to return two values:
public class Pair<U, V> {
/**
* The first element of this <code>Pair</code>
*/
private U first;
/**
* The second element of this <code>Pair</code>
*/
private V second;
/**
* Constructs a new <code>Pair</code> with the given values.
*
* #param first the first element
* #param second the second element
*/
public Pair(U first, V second) {
this.first = first;
this.second = second;
}
//getter for first and second
and then have the method return that Pair:
public Pair<Object, Object> getSomePair();
You can only return one value in Java, so the neatest way is like this:
return new Pair<Integer>(number1, number2);
Here's an updated version of your code:
public class Scratch
{
// Function code
public static Pair<Integer> something() {
int number1 = 1;
int number2 = 2;
return new Pair<Integer>(number1, number2);
}
// Main class code
public static void main(String[] args) {
Pair<Integer> pair = something();
System.out.println(pair.first() + pair.second());
}
}
class Pair<T> {
private final T m_first;
private final T m_second;
public Pair(T first, T second) {
m_first = first;
m_second = second;
}
public T first() {
return m_first;
}
public T second() {
return m_second;
}
}
Here is the really simple and short solution with SimpleEntry:
AbstractMap.Entry<String, Float> myTwoCents=new AbstractMap.SimpleEntry<>("maximum possible performance reached" , 99.9f);
String question=myTwoCents.getKey();
Float answer=myTwoCents.getValue();
Only uses Java built in functions and it comes with the type safty benefit.
Use a Pair/Tuple type object , you don't even need to create one if u depend on Apache commons-lang. Just use the Pair class.
you have to use collections to return more then one return values
in your case you write your code as
public static List something(){
List<Integer> list = new ArrayList<Integer>();
int number1 = 1;
int number2 = 2;
list.add(number1);
list.add(number2);
return list;
}
// Main class code
public static void main(String[] args) {
something();
List<Integer> numList = something();
}
public class Mulretun
{
public String name;;
public String location;
public String[] getExample()
{
String ar[] = new String[2];
ar[0]="siva";
ar[1]="dallas";
return ar; //returning two values at once
}
public static void main(String[] args)
{
Mulretun m=new Mulretun();
String ar[] =m.getExample();
int i;
for(i=0;i<ar.length;i++)
System.out.println("return values are: " + ar[i]);
}
}
o/p:
return values are: siva
return values are: dallas
I'm curious as to why nobody has come up with the more elegant callback solution. So instead of using a return type you use a handler passed into the method as an argument. The example below has the two contrasting approaches. I know which of the two is more elegant to me. :-)
public class DiceExample {
public interface Pair<T1, T2> {
T1 getLeft();
T2 getRight();
}
private Pair<Integer, Integer> rollDiceWithReturnType() {
double dice1 = (Math.random() * 6);
double dice2 = (Math.random() * 6);
return new Pair<Integer, Integer>() {
#Override
public Integer getLeft() {
return (int) Math.ceil(dice1);
}
#Override
public Integer getRight() {
return (int) Math.ceil(dice2);
}
};
}
#FunctionalInterface
public interface ResultHandler {
void handleDice(int ceil, int ceil2);
}
private void rollDiceWithResultHandler(ResultHandler resultHandler) {
double dice1 = (Math.random() * 6);
double dice2 = (Math.random() * 6);
resultHandler.handleDice((int) Math.ceil(dice1), (int) Math.ceil(dice2));
}
public static void main(String[] args) {
DiceExample object = new DiceExample();
Pair<Integer, Integer> result = object.rollDiceWithReturnType();
System.out.println("Dice 1: " + result.getLeft());
System.out.println("Dice 2: " + result.getRight());
object.rollDiceWithResultHandler((dice1, dice2) -> {
System.out.println("Dice 1: " + dice1);
System.out.println("Dice 2: " + dice2);
});
}
}
You don't need to create your own class to return two different values. Just use a HashMap like this:
private HashMap<Toy, GameLevel> getToyAndLevelOfSpatial(Spatial spatial)
{
Toy toyWithSpatial = firstValue;
GameLevel levelToyFound = secondValue;
HashMap<Toy,GameLevel> hm=new HashMap<>();
hm.put(toyWithSpatial, levelToyFound);
return hm;
}
private void findStuff()
{
HashMap<Toy, GameLevel> hm = getToyAndLevelOfSpatial(spatial);
Toy firstValue = hm.keySet().iterator().next();
GameLevel secondValue = hm.get(firstValue);
}
You even have the benefit of type safety.
Return an Array Of Objects
private static Object[] f ()
{
double x =1.0;
int y= 2 ;
return new Object[]{Double.valueOf(x),Integer.valueOf(y)};
}
In my opinion the best is to create a new class which constructor is the function you need, e.g.:
public class pairReturn{
//name your parameters:
public int sth1;
public double sth2;
public pairReturn(int param){
//place the code of your function, e.g.:
sth1=param*5;
sth2=param*10;
}
}
Then simply use the constructor as you would use the function:
pairReturn pR = new pairReturn(15);
and you can use pR.sth1, pR.sth2 as "2 results of the function"
You also can send in mutable objects as parameters, if you use methods to modify them then they will be modified when you return from the function. It won't work on stuff like Float, since it is immutable.
public class HelloWorld{
public static void main(String []args){
HelloWorld world = new HelloWorld();
world.run();
}
private class Dog
{
private String name;
public void setName(String s)
{
name = s;
}
public String getName() { return name;}
public Dog(String name)
{
setName(name);
}
}
public void run()
{
Dog newDog = new Dog("John");
nameThatDog(newDog);
System.out.println(newDog.getName());
}
public void nameThatDog(Dog dog)
{
dog.setName("Rutger");
}
}
The result is:
Rutger
You can create a record (available since Java 14) to return the values with type safety, naming and brevity.
public record MyResult(int number1, int number2) {
}
public static MyResult something() {
int number1 = 1;
int number2 = 2;
return new MyResult(number1, number2);
}
public static void main(String[] args) {
MyResult result = something();
System.out.println(result.number1() + result.number2());
}
First, it would be better if Java had tuples for returning multiple values.
Second, code the simplest possible Pair class, or use an array.
But, if you do need to return a pair, consider what concept it represents (starting with its field names, then class name) - and whether it plays a larger role than you thought, and if it would help your overall design to have an explicit abstraction for it. Maybe it's a code hint...
Please Note: I'm not dogmatically saying it will help, but just to look, to see if it does... or if it does not.
Let A be an interface which has a method a.
Let B be a class which implements A and has method a and has three fields 1,2,3.
I want to use two instances of A (meaning B), both of which have different values of 1,2,3 (present in cfg file) at two different places.
Can someone provide a simple and elegant solution to this problem using Guice.
You don't tell how the class that uses your dependency references the interface. I assume that you want to reference it with an interface.
What you can use, is annotation that will denote which instance you want to use. Assume that these are your implementations:
interface A {
void a();
}
class B implements A {
private int value;
void a() { ... }
B(int value) { this.value = value; }
}
And these are the classes that use the implementations:
class UserFirst {
private A a;
#Inject
UserFirst(#Named("first") A a) { this.a = a; }
}
class UserSecond {
private A a;
#Inject
UserSecond(#Named("second") A a) { this.a = a; }
}
The thing that decides which implementation is going to be injected is the #Named annotation. You can also define your annotations, but usually it's an overkill.
Now, in order to bind that, you can do something like this:
class MyModule extends AbstractModule {
#Override
protected void configure() {
A first = new B(1);
B second = new B(2);
bind(A.class)
.annotatedWith(Names.named("first")).toInstance(first);
bind(A.class)
.annotatedWith(Names.named("second")).toInstance(second);
}
}
Here's the full documentation: https://github.com/google/guice/wiki/BindingAnnotations
if I do understand you correctly, you might want to make B abstract so that you can override the methods which you want to change, if this is the case.
Now I can only assume that by fields you mean field-varriables. I would then recommend you to make them NON-static and change them in the constructor when you make an object. Then read the values of 1,2,3 in the public static void main method and send them upon creating a new object:
public class B implements A {
private int x,y,z;
/**
* This would now be the constructror
*/
public B(int x, int y, int z){
this.x = x;
this.y = y;
this.z = z;
}
/**
* Then some return functions
*/
public get1() { return this.x; }
public get2() { return this.y; }
public get3() { return this.z; }
/**
* Then whatever methods you get from A
*/
public int someMethodFromA(int x, int y){
return x*y;
}
}
public static void main(String[] args) {
/**
* Some random method to read inn from CFG file
*/
int x1 = readXFromCFG();
int y1 = readYFromCFG();
int z1 = readZFromCFG();
B objectB1 = new B(x1,y1,z1);
int x2 = readXFromCFG();
int y2 = readYFromCFG();
int z2 = readZFromCFG();
B objectB2 = new B(x2,y2,z2);
int x3 = readXFromCFG();
int y3 = readYFromCFG();
int z3 = readZFromCFG();
B objectB3 = new B(x3,y3,z3);
}
So I've seen, in many places, calling methods of a class like:
SomeClass obj = new SomeClass();
obj.addX(3).addY(4).setSomething("something").execute();
I don't think I completely understand how that works. Is each method independent of each other, so the above is equal to:
obj.addX(3);
obj.addY(4);
obj.addSomething("something");
obj.execute();
Or are they designing their class structure in some other fashion that allows for this. If they are how are they designing their classes to support this?
Also, does that have a specific name? Or is this just calling methods on a class?
That would be method chaining. It can do one of two things.
Each call to a method returns this which allows you to continue to call methods on the original instance.
public class SomeClass
{
private int _x = 0;
private int _y = 0;
private String _something = "";
public SomeClass addX(int n)
{
_x += n;
return this;
}
public SomeClass addY(int n)
{
_y += n;
return this;
}
public SomeClass setSomething(String something)
{
_something = something;
return this;
}
// And so on, and so on, and so on...
}
Each method call returns a new instance of the class with everything copied/updated appropriately. This makes the class immutable (so you don't accidentally modify something that you didn't mean to).
public class SomeClass
{
private int _x = 0;
private int _y = 0;
private String _something = "";
public SomeClass(int x, int y, String something)
{
_x = x;
_y = y;
_something = something;
}
public SomeClass addX(int n)
{
return new SomeClass(_x + n, _y, _something);
}
public SomeClass addY(int n)
{
return new SomeClass(_x, _y + n, _something);
}
public SomeClass setSomething(String something)
{
return new SomeClass(_x, _y, something);
}
// And so on, and so on, and so on...
}
Some people have also mentioned Fluent Interfaces. Fluent Interfaces utilize method chaining to create an API that provides something along the lines of a Domain Specific Language which can make code read much more clearly. In this case, your example doesn't quite qualify.
they modify object's state and return the same object back mostly
class Number{
int num;
public Number add(int number){
num+=number;
return this;
}
}
you can call it like
new Number().add(1).add(2);
most of the time the use case is to return new Object to support immutability
Each of those methods return an instance. For example, the call to
obj.addX(3)
will return the same instance obj, so the call
obj.addX(3).addY(4)
will be equivalent to
obj.addY(4)
This is called method chaining.
The methods are implemented like this:
public SomeClass addX(int i) {
// ...
return this; // returns the same instance
}
public class Test1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Test1 abc = new Test1();
abc.add1(10, 20).sub1(40, 30).mul1(23, 12).div1(12, 4);
}
public Test1 add1(int a, int b)
{
int c = a + b;
System.out.println("Freaking Addition output : "+c);
return this;
}
public Test1 sub1(int a, int b)
{
int c = a - b;
System.out.println("Freaking subtraction output : "+c);
return this;
}
public Test1 mul1(int a, int b)
{
int c = a * b;
System.out.println("Freaking multiplication output : "+c);
return this;
}
public Test1 div1(int a, int b)
{
int c = a / b;
System.out.println("Freaking divison output : "+c);
return this;
}
}
I want to have a list of constants like A, B, C related to integers 1, 2, 3
I know you can do like
class Example {
public static final int A = 1;
etc...
}
and
enum Example {
A(1), ... etc;
some initialization of an integer
}
But is there a way to do it like the public static final but as succinct as enums? When I use A and I really mean 1 I don't want to call Example.A.value or something like that.
One way would be to use an interface, where variables are public, static and final by default:
interface Example {
int A = 1;
int B = 2;
}
If I understand what you're asking correctly, you want to do something like this:
enum Example {
A = 1,
B = 2,
....
}
There is no nice simple syntax for this.
You either have to write out some constants:
public interface Example {
public static final int A = 1;
public static final int B = 2;
....
}
...Or you can add some other value to the enum:
public enum Example {
A(1),
B(2)
....
private final int val;
public Example (int val) {
this.val = val;
}
public int getValue() {
return val;
}
}
I think the shortest solution is:
public static final int A = 1, B = 2, C = 3;
If you really want to use Enum, then you can override toString() method in your enum, to get the value printed when you print your Enum Instance: -
enum Example {
A(1), B(2);
private int val;
private Example(int val) {
this.val = val;
}
#Override
public String toString() {
switch (this) {
case A:
return String.valueOf(val);
case B:
return String.valueOf(val);
}
return super.toString();
}
}
public class D {
public static void main(String[] args) {
Example a = Example.A;
Example b = Example.B;
System.out.println(a); // Prints 1
System.out.println(b); // Prints 2
}
}
Ideally your above enum is just like the below class: -
class Example {
public static final int A = 1;
public static final int B = 2;
}
So, I don't see the necessity of using Enums..