I have a method A in class Test, which generates a number a and b, heres the code for it:
public class Test
{
int a,b;
public void A()
{
a = currentMenu.getCurrentFocusedItem().getItemID();
b = currentMenu.getMenuID();
System.out.println("Inside A ()" + a + " &&" + b);
}
public void B()
{
System.out.println("Inside B ()" + a + " &&" + b);
}
}
Now, I want to acces the a and b int values, into another method B(), in the same
class file.
Need some pointer
If you are working with the same instance of the class Test, the value of a and b as set in method A() should still be visible in method B().
So, the below would work:
Test test = new Test();
test.A();
test.B();
However, the below wouldn't
new Test().A();
new Test().B();
On a side note, methods in Java should always begin with a lowercase letter and use camelcase.
If what you are trying to do is to get the current(and latest) value of a and b,
you could write 2 methods like
public int getA() {
return currentMenu.getCurrentFocusedItem().getItemID();
}
public int getB() {
return currentMenu.getMenuID();
}
and use these methods instead of calling A() to update the values of a,b and then accessing them again in method B.
you can get the a and b values in instance initialization block
public class TestClass {
int a,b;
{
a= 10;
b =45;
}
public void A() {
System.out.println("Inside A ()" + a + " &&" + b);
}
public void B() {
System.out.println("Inside B ()" + a + " &&" + b);
}
}
Using this method, you don't have to call your A() method for populating the values to be used in B()
You can try this too
public void A()
{
a = currentMenu.getCurrentFocusedItem().getItemID();
b = currentMenu.getMenuID();
System.out.println("Inside A ()" + a + " &&" + b);
}
public void B()
{
Test test=new Test();
test.A(); // assign values for a and b
System.out.println("Inside B ()" + a + " &&" + b);
}
Related
Suppose i have 2 interface which is
interface add{
void add2No(float a, float b);
}
and
interface Minus{
void Minus2No(float a, float b);
}
then on the main method, i already overide the method which is
public class Count implements Add, Minus {
public static void main(String[] args) throws IOException{
//declare var
float a, b;
String temp;
//create object
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Count obj = new Count();
//User Input
System.out.print("Enter your first Number : ");
temp = br.readLine();
a = Float.parseFloat(temp);
System.out.print("Enter your second Number : ");
temp = br.readLine();
b = Float.parseFloat(temp);
System.out.println("Value of " +a+ " + " +b+ " is : " +obj.Totaladd(float a, float b));
System.out.println("Value of " +a+ " + " +b+ " is : " +obj.TotalMinus(float a, float b));
}
#Override
public void Add2No(float a, float b) {
float TotalAdd = a + b;
}
#Override
public void Minus2No(float a, float b) {
float TotalMinus = a - b;
}
}
Am i using the correct implementation for interface? why there's error when i try to print out the TotalAdd and TotalMinus?
Yes. Because you don't return the results. Currently both methods are void. You could change that. Like,
interface Add {
float add2No(float a, float b);
}
interface Minus {
float minus2No(float a, float b);
}
And then
#Override
public float add2No(float a, float b) {
return a + b;
}
#Override
public float minus2No(float a, float b) {
return a - b;
}
There are three wrong places.
The first wrong place:
Because Java is case sensitive.
The name of your interface method is called add2No, but the name of
your implementation is called Add2No
The second wrong place:
There is a problem with your method parameter passing and the way of
calling. I did not see the Totaladd and Totaladd methods defined in
your Count object.
If you adjust the case, there should only be add2No and Minus2No
methods in Count object.
You need to adjust the name of one of them, and do not pass the type when passing parameters.
For example: obj.Totaladd(float a, float b) should be obj.Totaladd(a, b)
The third wrong place:
If you need to call the method to get the value for calculation, you must adjust the type of the method, it should not be void
I have two classes and, in one of them, I want to create a variable that will hold a function from the other class. I want to do this so I can change behaviour dinamically conditionally.
I tried the following prototype which results in a compilation error:
class A {
public String myFn(int a, int b) {
return "<" + a + " " + b + ">";
}
public String myFn2(int a, int b) {
return "(" + a + " " + b + ")";
}
}
class B {
static int mode = 1;
public void fn() {
BiFunction<Integer, Integer, String> fn = null;
if(mode == 1) {
fn = ClassA.myFn(); // This results in an error "Cannot resolve method fn()".
}
else {
//fn = ClassA.myFn2();
}
// next I will use fn ...
}
}
This results in an error "Cannot resolve method fn()".
How can I store the function?
Thanks.
Calling ClassA.myFn() would require the method to be static and this is a method call, you wan't to store the method, not calling it.
Lambda
BiFunction<Integer, Integer, String> fn = null;
if(mode == 1) {
fn = (a, b) -> ClassA.myFn(a, b);
}
Method reference
BiFunction<Integer, Integer, String> fn = null;
if(mode == 1) {
fn = ClassA::myFn;
}
⚠️ Also
both myFn and myFn2 should be static
public static String myFn(int a, int b) {
return "<" + a + " " + b + ">";
}
chosse ClassA or A but they should be matching
class ClassA {
Your method myFn is not static, so you can't access it in a static context like you are trying to do. Your class is also called A, but you reference it as ClassA. Also, when assigning the BiFunction, you assign it to the return value, when you want a lambda expression. Here's an edited copy of your example:
class A {
public static String myFn(int a, int b) { //notice the static keyword
return "<" + a + " " + b + ">";
}
public static String myFn2(int a, int b) { //notice the static keyword
return "(" + a + " " + b + ")";
}
}
class B {
static int mode = 1;
public void fn() {
BiFunction<Integer, Integer, String> fn = null;
if(mode == 1) {
fn = A::myFn; // use a lambda expression, and class is named A
}
else {
//fn = A::myFn2;
}
// next I will use fn ...
}
}
So this is basically my code
abstract class B
{
int x = 3;
B()
{
x+=2;
System.out.print("-x" + x + "\n"); // print -x5
x++; // 5 then 6
}
abstract int calculate();
abstract int calculate(int i);
}
class A extends B
{
int x = 2;
A()
{
System.out.print("-x" + calculate(2)+"\n");
}
#Override
int calculate()
{
return x;
}
#Override
int calculate(int i)
{
return(calculate()+i);
}
}
public class Test2 extends A
{
Test2()
{
x+=3;
}
#Override
int calculate()
{
return x + 6;
}
public static void main(String[] args) {
Test2 sub = new Test2();
System.out.print("-x" + sub.calculate()+"\n");
}
}
My problem here is after digging up about variable hiding I learned that if a instance variable is of the same name in both parent class and child class then the childclass hides the instance variable of the parent class. Also I have the prior knowledge that variables cannot be overridden when child class inherits parent class.
So now coming to the problem, in the code when A extends to B, why does the print statement inside constructor A() gives a value -x10? shouldn't it be -x8?? I dont understand how the variable is being changed here. I am new to java so any kind of knowledge will be greatly appreciated. :)
Ok so I have done some debugging and found that the calculate(void) method in class A returns 8. But how is that possible shouldn't it return 6? Please help!
The reason it prints -x10 is because A::calculate(2) calls the Test2::calculate(), which uses A::x to do the calculation.
The sequence of calls that happens is the following:
Test2() {
A()
B() {
B::x = 3
B::x += 2
System.out.print("-x" + x + "\n"); // print -x5
B::x++ // B::x is now 6
}
A::x = 2
System.out.print("-x" + calculate(2)+"\n")
A::calculate(2) {
return(calculate()+2);
Test2::calculate() {
return A::x + 6; // A::x is 2 here, so returns 8
}
} // returns calculate()+2, so returns 10
}
A::x += 3
}
I hope this is just code to test things out, because you should never allow this to happen in real code. You should never allow a method of a subclass to be called from the constructor of a base class, because the subclass is not initialised at that time. The Java compiler does its best to prevent that, but sometimes it does not detect it.
It is returning 8 because:
The line you called System.out.print("-x" + sub.calculate()+"\n"); in class A calls
#Override
int calculate()
{
return x + 6;
}
in class A still, which is incrementing the instance variable int x = 2 in class A . this variable overwrote the one in class B
Hence 2+6 = 8
I am new to Java so I need help.
How can I access the variables of the method method1 and compare them with the variable int c? What should I return?
public static void main (String [] args){
int c = 30;
// I want to compare c with a, for example:
if (c > a)
{
System.out.println(c + " is greater than " + a);
}
}
I want to do the above comparison without touching method1()
public double method1(){
int a = 10; int b = 20;
if (a > b)
{
System.out.println(a + " is greater than " + b);
}
else if (a < b)
{
System.out.println(b + " is greater than " + a);
}
//What should I return?
return ????;
}
if you are writing "int c = 30;" directly below main then it becomes global variable.
Global Variable means: "c" can be accessed inside methods(anywhere in same class).
if you are writing "int c = 30;" inside particular method than you cannot access outside that particular method.
Following is example of global variable.
public static void main (String [] args){
int c = 30;
public double method1(){
int a = 10;
if (a > c)
{
System.out.println(a + " is greater than " + c);
return a;
}
else if (a < c)
{
System.out.println(c + " is greater than " + a);
return b;
}
}
I hope it works for you.
How can I access the variables of the method "method1" [...] without touching the method1()?
You can't.
Local variables in a method are only accessible inside that method. And if that method doesn't give you a way to see them, then without modifying the method, you can't see them.
Since a is always 10, you could do if (c > 10) instead.
I am new to Java, I have below code, and getting exception like
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Cannot instantiate the type Calculator2Service
The method getCalculator2Port() is undefined for the type Calculator2Service
at com.theopentutorials.ws.calc2.client.Calc2Client.main(Calc2Client.java:13)
Please some one help..
package com.theopentutorials.ws.calc2.client;
import com.theopentutorials.ws.calc2.*;
public class Calc2Client {
/**
* #param args
*/
public static void main(String[] args) {
int a = 10;
int b = 12;
Calculator2Service calcService = new Calculator2Service();
Calculator2 calc = calcService.getCalculator2Port();
System.out.println(a + " + " + b + " = " + calc.add(a, b));
System.out.println(a + " - " + b + " = " + calc.sub(a, b));
}
}
You should define getCalculator2Port in the class Calculator2Service. If you're sure you've done this, please check the spells and note that Java is a case sensitive language.
BTW you may want to access getCalculator2Port while it's not visible in this scope, e.g. it's a private method, however in this case you get notified as "The method ... from the type ... is not visible".
Calculator2Port is a factory method which returns a Calculator2 object here. You should define an interface or abstract class like
public interface Calculator2 {
public double add(double a, double b);
public double sub(double a, double b);
}
then in Calculator2Service should have a method like
Calculator2 getCalculator2Port(){
Calculator2 c = new Calculator2(){
public double add(double a,double b){
return(a+b);
}
public double sub (double a, double b){
return(a-b);
}
}
return(c);
}