How to instantiate an object in java? - 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();

Related

Getting a new variable with custom output and not a constructor location (name#xxxxx) - Java

I've been trying to make a custom output from the constructor in Java, but it keeps giving me the location of it. The return does not work and throws up an error. The code is:
Public class Example {
public static int a, b;
Example(int inputForA, int inputForB){
a = inputForA;
b = inputForB;
}
}
The output i want is a/b (a fraction, for example 3/2).
I tried a return command, but it does not work:
Public class Example {
public static int a, b;
Example(int inputForA, int inputForB){
a = inputForA;
b = inputForB;
return a +"/"+ b; //i even tried making String Example(){...} in the beginning but it still does not work, throws an error
}
}
The output i'm getting, when i am trying to print Example (3, 2)System.out.println(Example(3, 2)) is Example#4dd8dc3 and as mentioned i need 3/2.
Is there a way to do it?
Thanks!
Example is a class, not a method. It's like a template for an object.
But you can put a method in that class that returns what you want.
Example.java
package myPackage;
public class Example
{
public static int a, b;
Example(int inputForA, int inputForB)
{
a = inputForA;
b = inputForB;
}
float compute ()
{
return (float)a/(float)b;
}
}//_Example
Now we create an instance of Example and use this object in another class.
Main.java
package myPackage;
public class Main
{
public static void main(String []args)
{
Example exp = new Example (3, 2);
System.out.println(exp.compute());
}//_main
}//_Main

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

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

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

Set and get a static variable from two different classes in Java

Lets say I have 3 Classes: A, Data, and B
I pass a variable from class A which sets that passed variable to a private variable in class Data.
Then in class B, I want to call that specific variable which has been changed.
So I do
Data data = new Data();
data.getVariable();
It will then return null, since in class Data I initialize variables to nothing (ex: int v;), and I think that class B is initializing a brand new class and resetting the values to default, but I don't know how to fix this.
I know that the variable is setting properly because in class A if I do data.getVariable() it will print the variable that was set.
Class A:
Data data = new Data();
int d = 1;
data.setVariable(d);
Class Data:
private static int b;
public void setVariable(int s)
{
b = s;
}
public int getVariable()
{
return b;
}
Class B:
Data data = new Data();
private int v;
v = data.getVariable();
System.out.println(v);
This will print out 0 instead of the actual value
When you instantiate a Data object in class A, and instantiate another Data object in class B, they are two different instances of the Data class. They both instantiate d to 0 by default. You then call setVariable on the instance in class A and pass it the value of 1; but the instance in class B remains in 0. In order to change the value of the instance in class B, you would need to call setVariable on the instance in class B.
What it seems like you're looking for is a static member. Static members are the same across all instances of the same class. Just put the static keyword before the method(s) or field(s) that you want to use it. Static members and fields are typically accessed using the name of the class in which they are declared (i.e. MyClass.doMethod()). For example:
Class Data (updated):
private static int b;
public static void setVariable(int s)
{
b = s;
}
public static int getVariable()
{
return b;
}
Class A:
Data.setVariable(d);
Class B:
v = Data.getVariable();
System.out.println(v);
Editing - my first suggestion was to use static for variable b, and the author changed his question adding that suggestion.
It fixes what you are trying to do. I write the example in code that compiles:
public class Demo {
public static void main(String[] args) {
A a = new A();
B b = new B();
a.doWhatever();
b.doSomethingElse();
}
}
class Data {
private static int b;
public void setVariable(int s)
{
b = s;
}
public int getVariable()
{
return b;
}
}
class A {
public void doWhatever() {
Data data = new Data();
int d = 1;
data.setVariable(d);
}
}
class B {
Data data = new Data();
private int v;
public void doSomethingElse() {
v = data.getVariable();
System.out.println(v);
}
}

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