I've been using multiple methods, but my "java the complete reference" book doesn't do a good job of explaining how to use the "this" keyword.
this in java
It is used to refer to the data members of the object in the envoked method or constructor in case there is a name conflict between fields and local variables
public class Test {
String s;
int i;
public Test(String s, int i){
this.s = s;
this.i = i;
} }
It is used to invoke one constructor from another constructor of the same class or you can say constructor chaining.
public class ConstructorChainingEg{
String s;
int i;
public ConstructorChainingEg(String s, int i){
this.s = s;
this.i = i;
System.out.println(s+" "+i);
}
public ConstructorChainingEg(){
this("abc",3); // from here call goes to parameterized constructor
}
public static void main(String[] args) {
ConstructorChainingEg m = new ConstructorChainingEg();
// call goes to default constructor
}
}
It also facilitates method chaining
class Swapper{
int a,b;
public Swapper(int a,int b){
this.a=a;
this.b=b;
}
public Swapper swap() {
int c=this.a;
this.a=this.b;
this.b=c;
return this;
}
public static void main(String aa[]){
new Swapper(4,5).swap(); //method chaining
}
}
Here's a couple:
public class Example {
private int a;
private int b;
// use it to differentiate between local and class variables
public Example(int a, int b) {
this.a = a;
this.b = b;
}
// use it to chain constructors
public Example() {
this(0, 0);
}
// revised answer:
public int getA() {
return this.a;
}
public int getB() {
return this.b
}
public int setA(int a) {
this.a = a
}
public void setB(int b) {
this.b = b;
}
}
this refers to the attributes that belong to the object in which this is used in. For example:
Example ex1 = new Example(3,4);
Example ex2 = new Example(8,1);
In these cases, ex1.getA() will return 3, because this is referring to the a that belongs to the object named ex1, and not ex2 or anything else. The same goes for ex2.getB().
If you look at the setA() and setB() methods, using this distinguishes the attributes a and b belonging to the object from the parameter names as they're the same.
Related
Suppose i have classes A,B,C. C has a method longRunningMethod, which takes a long time to run and returns an int. Classes A and B both have C as a dependency and need to call method longRunningMethod:
public class A{
private C c;
public A(C c){
this.c = c;
}
public void method1(){
this.c.longRunningMethod();
}
}
public class B{
private C c;
public A(C c){
this.c = c;
}
public void method2(){
this.c.longRunningMethod();
}
}
public class C{
public int longRunningMethod(){
...
}
}
public class MyProgram{
public static void main(String[] args){
C c = new C();
A a = new A(c);
B b = new B(c);
a.method1();
b.method2()//avoid calling c.longRunningMethod();
}
}
What approaches can be taken to avoid calling longRunningMethod twice? Of course, the simple approach is to change the constructor argument of A and B to int and call longRunningMethod once in MyProgram. But then, it is not that obvious to what to pass to A and B (which ints are allowed?).
public class C{
private boolean wasCalled = false;
private int cachedValue;
public int longRunningMethod(){
if (!wasCalled) {
// do your long running job here and set result to cachedValue
wasCalled = true;
}
return cachedValue;
}
}
When I run this code, I get the error "Cannot find symbol" on the 'getNum2' in the add method of the A class. How do I make it so that one class can use objects/methods from another class.
I think it would work if I placed that method in the main class, but I want to be able to call the "add" method for different objects and not have it hard coded for one set of values.
class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
A a = new A(1);
B b = new B(2);
}
}
public class A {
private int num1;
public A(int num){
num1=num;
}
public int getNum1(){
return num1;
}
public int add (){
return getNum1()+getNum2();
}
}
public class B{
private int num2;
public B (int num){
num2=num;
}
public int getNum2(){
return num2;
}
}
Your add method is inside of A. That means you have access to A's methods, such as getNum1. If you want to call B's methods inside of add, then you need access to an instance of B there. You can simply pass that instance as a parameter:
public int add (B b){
return getNum1()+b.getNum2();
}
In your main you can then call it like
int sum = a.add(b);
Your A class doesn't have a getNum2() method, nor does it have an instance of B.
Change the add method in A to:
public int add(int toAdd) {
return num + toAdd;
}
and use it like this:
A a = new A(1);
B b = new B(2);
int result = a.add(b.getNum2());
To call getNum2() method inside Class A first you need to create an object of Class B inside the Class A or you need a reference to a Class B object.
Otherwise, you can you should specify getNum2() method as a static method.
Create an Object of Class B inside Class A.
class A{
private int num;
int getNum1(){
return num;
}
public int add(){
B b = new B();
return getNum1() + b.getNum2();
}
}
Specify getNum2() as static
class A{
private int num;
int getNum1(){
}
public int add(){
return getNum1() + B.getNum2();
}
}
class B{
static int num;
public static int getNum2(){
return num;
}
}
Please remember, terminologies I have used are in a very simple way as you can understand. Not in the best way. Also, I have skipped the constructors you have used to make this much more understandable.
You better study more on basic OOP concepts of Java. BTW, Good Luck!
This is the code that is more related to your code.
public class Main{
public static void main(String[] args) {
A a = new A(2);
B b = new B(3);
a.add(b);
}
}
class A{
private int num;
public A(int num){
this.num = num;
}
int getNum1(){
return num;
}
public int add(B b){
return getNum1() + b.getNum2();
}
}
class B{
private int num;
public B(int num){
this.num = num;
}
public int getNum2(){
return num;
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I want to make sum of two numbers. But I have problems to do that. I don't understand why my sum is always zero.
class A
public class A {
int a=3 ,b=4;
public static void main(String[] args) {
B obj= new B();
obj.prod();
}
}
CLASS B
public class B {
int a, b;
public void prod()
{
System.out.print(a+b);
}
}
Uninitialized primitive fields have a default value. In the case of int this value is 0.
To pass the values from class A to B you should implement a constructor which takes two arguments.
public class B {
int a, b;
public B(int a, int b)
{
this.a = a;
this.b = b;
}
public void prod()
{
System.out.print(a+b);
}
}
Then in your class A, call the constructor of B like this:
public class A {
int a=3 ,b=4;
public static void main(String[] args) {
B obj= new B(a, b);
obj.prod();
}
}
Another way is to give your method prod() the parameters:
public void prod(int a, int b)
{
System.out.print(a+b);
}
And then call it:
public class A {
int a=3 ,b=4;
public static void main(String[] args) {
B obj= new B();
obj.prod(a, b);
}
}
public class A {
int a=3 ,b=4;
public static void main(String[] args) {
B obj= new B();
obj.prod(a,b);
}
}
public class B {
public void prod(int a, int b)
{
System.out.print(a+b);
}
}
I think the below code will help you:
public class A {
public static void main(String[] args) {
// create object B, passing aa=3, bb=4 to B's constructor
B objectB = new B(3, 4);
// this will return result as "12"
int result = objectB.prod();
}
}
public class B {
// declare member variables
private final int a;
private final int b;
// B's constructor
public B (int aa, int bb) {
// set values passed in to member variables
this.a = aa;
this.b = bb;
}
public int prod() {
int result = this.a + this.b;
// print result
System.out.print(result + "");
// return result to caller
return result;
}
}
You are initializing the values in class A. These are not available in class B. Either pass in constructor of class B or pass to the method prod().
You need to modify your class as below :
public class A {
int a = 3, b = 4;
public static void main(String[] args) {
B obj = new B(a, b);
obj.prod();
}
}
public class B {
int a, b;
b(int a, int b) {
this.a = a;
this.b = b;
}
public void prod() {
System.out.print(a + b);
}
}
//OR
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class A {
int a = 3, b = 4;
public static void main(String[] args) {
B obj = new B();
obj.prod(a, b);
}
}
//CLASS B
public class B {
int a, b;
public void prod(int a, int b) {
System.out.print(a + b);
}
}
error: mul(int,int) has protected access in Multiplication
Thoughts on what I'm doing wrong?
public class Multiplication{
protected int mul(int a,int b){
return (a*b);
}
}
class ImplimentPkg extends Multiplication {
public static void main(String args[]){
Multiplication obj=new ImplimentPkg();
//Here's the error
System.out.println(obj.mul(2,4));
}
protected int mul(int a,int b){
System.out.println("");
return 0;
}
}
Java tutorial says:
The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.
You may think you have matched the second case(inheritence).
Multiplication obj = new ImplimentPkg();
System.out.println(obj.mul(2, 4));
This means you are using an instance of parent class Multiplication. Although the code is inside a method of subclass of Multiplication. It doesn't mean the instance obj has something to do with inheritance. And of course the mul(...) method is invisible. What you can do is: use keyword super.
public void bar() {
Multiplication mul = new Multiplication();
mul.mul(1, 2); // <- error
super.mul(1, 2); // correct
Multiplication.foo(); // correct
}
Note: if you have protected static method in parent class, like:
public class Multiplication {
private String name = "some";
protected int mul(int a, int b) {
return (a * b);
}
protected static void foo() {
System.out.println("foo");
}
}
Here the foo() method can be accessed everywhere in subclass, but not other classes. By the way, you shouldn't use protected static method, see reasons here.
Another related topic may be interested to you, see here.
Create each class in its own Java file
ImplimentPkg.java
package my;
class ImplimentPkg extends Multiplication {
public static void main(String args[]) {
Multiplication obj = new ImplimentPkg();
System.out.println(obj.mul(2, 4));
}
protected int mul(int a, int b) {
System.out.println("");
return 0;
}
}
Multiplication.java
package my;
public class Multiplication {
protected int mul(int a, int b) {
return (a * b);
}
}
I know it is impossible to override a method in one class. But is there a way to use a non-static method as static? For example I have a method which is adding numbers. I want this method to be usefull with an object and also without it. Is it possible to do something like that without creating another method?
EDIT:
What I mean is, if I make a method static I will need it to take arguments, and if I create an object with variables already set it will be very uncomfortable to call function on my object with same arguments again.
public class Test {
private int a;
private int b;
private int c;
public Test(int a,int b,int c)
{
this.a = a;
this.b = b;
this.c = c;
}
public static String count(int a1,int b1, int c1)
{
String solution;
solution = Integer.toString(a1+b1+c1);
return solution;
}
public static void main(String[] args) {
System.out.println(Test.count(1,2,3));
Test t1 = new Test(1,2,3);
t1.count();
}
}
I know the code is incorrect but i wanted to show what I want to do.
I want this method to be usefull with an object and also without it.
Is it possible to do something like that without creating another
method?
You will have to create another method, but you can make the non-static method call the static method, so that you do not duplicate the code and if you want to change the logic in the future you only need to do it in one place.
public class Test {
private int a;
private int b;
private int c;
public Test(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
public String count() {
return count(a, b, c);
}
public static String count(int a1, int b1, int c1) {
String solution;
solution = Integer.toString(a1 + b1 + c1);
return solution;
}
public static void main(String[] args) {
System.out.println(Test.count(1, 2, 3));
Test t1 = new Test(1, 2, 3);
System.out.println(t1.count());
}
}
But is there a way to use a non-static method as static?
No, it's not possible.
If you need this method to be used in static and non-static context, then make it static. The opposite configuration, however, is not possible.
Make it static, then it can be used with object and without it.
public class MyTest() {
public static int add() {
System.out.println("hello");
}
}
MyTest.add(); //prints hello
MyTest myobject = new MyTest();
myobject.add(); //prints hello