How can I use methods from another class in a class? - java

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;
}
}

Related

How to make a method with a return statement that is inside an abstract class which implements an interface get inherited by a subclass?

I will post the part of the code that I have trouble with. I scoured the internet for hours and cannot find a solution to how to properly solve this problem with a method that has a return and isn't just a sentence. I would seriously appreciate any help that I can get! Essentially what I need is for my subclass to inherit the same method in its abstract father without any changes, so that I can apply that in my main code.
public class Main {
interface Dodela
{
public int PovecajKS();
public int SmanjiS();
}
public static abstract class Ekspanzija implements Dodela
{
final public int PovecajKS(int a, int b)
{
a = a + b;
return a;
}
final public int SmanjiS(int a, int b)
{
a = a - b;
return a;
}
}
public static class EkspanzijaP extends Ekspanzija implements Dodela
{
public int PovecajKS()
{
}
public int SmanjiS() {
int a = 0, b = 0;
a = a - b;
return a;
}
}
It already inherits all methods of its father, to use the method inside the subclass, it can be called like this
super.yourFunctionName()

Static and non-static method in one class with the same name JAVA

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

How do I use the "this" keyword in java?

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.

How to instantiate an object in java?

I'm new in programming and I would like to know where did I go wrong in instantiating an object. Below is the code:
public class Testing{
private int Sample(int c)
{
int a = 1;
int b = 2;
c = a + b;
return c;
}
public static void main(String []args)
{
Sample myTest = new Sample();
System.out.println(c);
}
}
There is no Sample class in your code . The one which you have declared is a private method .
// private method which takes an int as parameter and returns another int
private int Sample(int c)
{
int a = 1;
int b = 2;
c = a + b;
return c;
}
With the current snippet , You need to instantiate the Testing class and make use of the Sample method. Notice your class definition is preceded by the keyword class , in this case class Testing.
public class Testing{
private int Sample(int c)
{
int a = 1;
int b = 2;
c = a + b;
return c;
}
public static void main(String []args)
{
Testing t = new Testing(); // instantiate a Testing class object
int result = t.Sample(1); // use the instance t to invoke a method on it
System.out.println(result);
}
}
But that doesn't really make sense, your Sample method always returns 3 .
Are you trying to do something like this :
class Sample {
int a;
int b;
Sample(int a, int b) {
this.a = a;
this.b = b;
}
public int sum() {
return a + b;
}
}
public class Testing {
public static void main(String[] args) {
Sample myTest = new Sample(1, 2);
int sum = myTest.sum();
System.out.println(sum);
}
}
I doubt you actually want to create an object.
From your code snippet, I understand that you want to run a 'method' named Sample which adds two numbers. And in JAVA you don't have to instantiate methods. Objects are instances of class. A method is just a behavior which this class has.
For your requirement, you don't need to explicitly instantiate anything as when you run the compiled code JAVA automatically creates an instance of your class and looks for main() method in it to execute.
Probably you want to just do following:
public class Testing{
private int sample(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int c = sample(1, 2);
System.out.println(c);
}
}
Note: I changed Sample to sample as it's generally accepted practice to start a method name with lower-case and class name with an upper-case letter, so Testing is correct on that front.
You instantiating correctly with new keyword ,But your calss name and method invoking is wrong
Testing myTest = new Testing();
int result =myTest.Sample(1); //pass any integer value
System.out.println(result );
Sample is not a class, it is just a method. You cannot create instances of it.
You only run it -
int sample = Sample(3);
If you wish for sample to be a class, define it as a class.
In your case, the method is not static is so you cannot directly access it from the Static method Main. Make it static so you could access it. Or just create a new instance of Testing and use it -
Testing testing = new Testing();
int sample = testing.Sample(3);
Sample method returns integer, so get the result and use it anywhere.
public static void main(String []args)
{
int myTest = Sample(4555);//input may be any int else
System.out.println(myTest);
}
This is how you should be doing this.
public class Testing{
public int Sample(int c)
{
int a = 1;
int b = 2;
c = a + b;
return c;
}
public static void main(String []args)
{
// Creating an Instance of Testing Class
Testing myTest = new Testing();
int c =0;
// Invoking the Sample() function of the Testing Class
System.out.println(myTest.Sample(c));
}
Well , it's easy. To you instantiate an object in Java you should to use class name and to do with that it class received a valor. For exemplo :
...Car c1 = new Car();

get super class value in java

I have 2 classes:
public class A
{
int n = 10;
public int getN()
{
return n;
}
}
public class B extends A
{
int n = 20;
public int getN()
{
return n;
}
}
public class Test
{
public static void main(String[] args)
{
B b = new B();
System.out.println(b.getN()); //--> return 20
System.out.println(((A)b).getN()); //--> still return 20.
//How can I make it return 10?
}
}
All methods in Java are always virtual. That is, there is no way of invoking the "super"-version of the method from the outside. Casting to A won't help as it doesn't change the runtime type of the object.
This is probably your best alternative / workaround:
class A {
int n = 10;
public int getN() {
return n;
}
public final int getSuperN() { // "final" to make sure it's not overridden
return n;
}
}
class B extends A {
int n = 20;
public int getN() {
return n;
}
}
public class Main {
public static void main(String[] args) {
B b = new B();
System.out.println(b.getN()); // --> return 20
System.out.println(((A)b).getN()); // --> still return 20.
System.out.println(b.getSuperN()); // --> prints 10
}
}
you can't make the value be "10" because the instance of the object was for class B, and when you do the cast the only thing that are you doing is changing the define class not setting values for the object B, in other words if you need to get 10 its' something like this
b = new A();
That thing won't work due to polymorphism. Class B is still class B even if you cast it into its super class.
I think you'll need something like this:
public class B extends A
{
int n = 20;
/**
* #return the super n
*/
public int getSuperN()
{
return super.n;
}
}
What you see is polymorphism in action. Since b is a B, that method (which returns 20) is always called (regardless if you cast it to an A).

Categories