error in calling a method in the same class - java

i tried compiling this basic code and can't get my main method to call another method. From my understanding, I don't have to create an object because both methods are in the same class.
However, it gives me the error- java: '.class' expected - when i call my method. anyone know why:
public class Main {
double x=0;
public static void main(String[] args) {
Function(double x);
}
public static double Function(double x) {
x+=5;
return x;
}
}

Look what you are doing in the main method:
public static void main(String[] args) {
Function(double x);
}
you are calling a method like Function(double x); but that is not correct, remove the type double, then you need to make the variable x static, because you are in an static context, after that just pass the argument x as parameter;
like:
static double x = 0;
public static void main(String[] args) {
Function(x);
}
Option2 is getting rid off static things and use instances...
class Main {
double x = 0;
public static void main(String[] args) {
Main m = new Main();
m.function(m.x);
}
public double function(double x) {
x += 5;
return x;
}
}

Non static variables can't be called from a static method. So call it by creating object of class in which the variable is declared.
public class Main {
double x=0;
public static void main(String[] args) {
Main mm=new Main(); //Creating Object of Class
Function(mm.x); //pass the value with object.var
}
public static double Function(double x) {
x+=5;
return x;
}
}

Related

Retrieve local variable value in another method in java

public class DemoClass {
public void setValue(int a, int b)
{
int x=a;
int y=b;
}
public void getValue()
{
}
public static void main(String[] args)
{
DemoClass dc=new DemoClass();
dc.setValue(10, 20);
dc.getValue();
}
}
In the above program I have two methods setValue() and getValue(). SetValue method has two variables x and y which are assigned values 10 and 20(from the main method).
Now I want to display the value of x and y variables in getValue() method. But this is not possible as they are local variables. Is there any possible way of doing this?
Is there any possible way of doing this?
The usual thing is to make them fields of the class, specifically instance fields:
public class DemoClass {
private int x; // These are
private int y; // instance fields
public void setValue(int a, int b)
{
this.x = a;
this.y = b;
}
public void getValue()
{
// Use `this.x` and `this.y` here
}
public static void main(String[] args)
{
DemoClass dc=new DemoClass();
dc.setValue(10, 20);
dc.getValue();
}
}
It's relatively rare to set two separate fields with a single setValue method, but there are use cases. Normally you'd have setX and setY (and getX and getY).
You could set them as public, or if you want to use getters and setters, you can do this.
public class DemoClass {
private int x;
private int y;
public void setValue(int a, int b)
{
this.x=a;
this.y=b;
}
public void getValue()
{
System.out.println(this.x);
System.out.println(this.y);
}
public static void main(String[] args)
{
DemoClass dc=new DemoClass();
tc.setValue(10, 20);
tc.getValue();
}
}
You can also put information in a constructor function like so:
public class DemoClass {
private int x;
private int y;
public DemoClass() {
this.x = 0; // default value
this.y = 0; // default value
}
public void setValue(int a, int b)
{
this.x=a;
this.y=b;
}
public void getValue()
{
System.out.println(this.x);
System.out.println(this.y);
}
public static void main(String[] args)
{
DemoClass dc=new DemoClass();
tc.setValue(10, 20);
tc.getValue();
}
}
That way, when you create the object like:
DemoClass demoClass = new DemoClass();
It will already have those objects set. If you don't do this and accidentally call getValue() and nothing is set, you will get a nullPointerException.

Define constructor in Java

I would like to know how can I define constructor in Java.
I started writing piece of code but I get errors.
package xyz;
public class ConstructorExample {
public static void main(String[] args) {
public ConstructorExample(int x,int y){
// private double x,y;
}
}
}
Can I write constructor in class with main or I must have another class? Thanks.
You cannot define a Constructor inside a method. You have to declare it like any other method in the class body.
package xyz;
public class ConstructorExample {
public ConstructorExample(int x,int y){
// private double x,y;
}
public static void main(String[] args) {
}
}
Of corse you can write a constructor for Main. Any class, enum and abstract class can have a constructor.
Simple usage
public Main(){
//Constructor code here...
}
Then to call main just use:
Main main = new Main ();
Note: private, protected and public modifiers can be used with a constructor.
The reason your getting an error in your code
Your attempting to create a method inside a method.
public static void main(String[] args){
public ConstructorExample(int x,int y){
//private double x,y;
}
}
Your attempting to create the constructor in your main method which is illigal syntax. The correct way to do it is:
class ConstructorExample {
//This is the constructor
public ConstructorExample(){
System.out.println("Constructor called");
}
public static void main(String [] args){
ConstructorExample example = new ConstructorExample();//This calls the constructor when creating the class
}
}
Your constuctor must be like any other method declared (but it has to be called same, as the class name, and do not provide any return):
public class ConstructorExample {
//this is your class fieald
private double x,y;
//here is the constructor
public ConstructorExample(int x,int y){
//set the class field's values, via this (means class),
//because the arg names is the same as fields names
this.x = x;
this.y = y;
}
public static void main(String[] args) {
//here is how you can create a class instance inside the main method
ConstructorExample example = new ConstructorExample(1,1);
}
}
Furthermore, if you have not defined any constructor, java will add the default one, without arguments. So it could look like:
public class ConstructorExample {
public static void main(String[] args) {
//here is how you can create a class instance inside the main method
//with the default constructor
ConstructorExample example = new ConstructorExample();
}
}
And if you have a number of constructors, then you can call one from another via this again, like:
public class ConstructorExample {
//this is your class fieald
private double x,y;
//here is the constructor with the single argument
public ConstructorExample(int x){
this.x = x;
}
//here is the constructor with 2 arguments
public ConstructorExample(int x,int y){
//you can call another constructor with the arguments
this(x);
this.y = y;
}
public static void main(String[] args) {
//here is how you can create a class instance inside the main method
ConstructorExample example = new ConstructorExample(1,1);
}
}
I would like to know how can I define constructor in Java. I started
writing piece of code but I get errors.
Error is because constructor is defined inside main() method. Need to move outside. You can call from main method.
Java constructors are special methods that are called when an object
is instantiated. In other words, when you use the new keyword. The
constructor initializes the newly created object.
package xyz;
public class ConstructorExample {
private int x;
private int y;
public ConstructorExample(int x,int y){
this.x = x;
this.y = y;
}
public static void main(String[] args) {
ConstructorExample example = new ConstructorExample(1,1);
}
}

java static binding and polymorphism

I am confused with the static binding example below. I reckon that S2.x and S2.y shows static binding as they prints out the fields according to s2's static type. And S2.foo() makes s2call the foo method in the super class, as foo is not over ridden in the subclass.
However with S2.goo(), isn't it supposed to call the goo() method in the Test1 subclass? Like it's polymorphism? How come it's static binding? It looks like S2.goo() calls the Super Class goo()method and prints out =13. Many thanks for your help in advance!
public class SuperClass {
public int x = 10;
static int y = 10;
protected SuperClass() {
x = y++;
}
public int foo() {
return x;
}
public static int goo() {
return y;
}
}
and SubClass
public class Test1 extends SuperClass {
static int x = 15;
static int y = 15;
int x2= 20;
static int y2 = 20;
Test1()
{
x2 = y2++;
}
public int foo2() {
return x2;
}
public static int goo2() {
return y2;
}
public static int goo(){
return y2;
}
public static void main(String[] args) {
SuperClass s1 = new SuperClass();
SuperClass s2 = new Test1();
Test1 t1 = new Test1();
System.out.println("S2.x = " + s2.x);
System.out.println("S2.y = " + s2.y);
System.out.println("S2.foo() = " + s2.foo());
System.out.println("S2.goo() = " + s2.goo());
}
}
In Java static variables and methods are not polymorphic. You can't expect polymorphic behavior with static fields.
Static methods can not be overridden, because they get bind with the class at compile time itself.
However, you can hide the static behavior of a class like this:
public class Animal {
public static void foo() {
System.out.println("Animal");
}
public static void main(String[] args) {
Animal.foo(); // prints Animal
Cat.foo(); // prints Cat
}
}
class Cat extends Animal {
public static void foo() { // hides Animal.foo()
System.out.println("Cat");
}
}
Output:
Animal
Cat
Refer link for method hiding in Java.
Also, take care that static method should not be called on instance as they get bind to Class itself.

java class why public static void main(String[] args) method can not access the property value of the class it is in?

public class Name{
int b = 100;
public void get(){
System.out.println(b);
}
public int num(){
return b;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(b);
}
}
get method can access b, num method can access b as well. why not public static void main method can access b.
Because b is an instance field, scoped within instances of the Name class.
Your main method is static, scoped within the class itself.
Declare b as static to be able to access it from the main method.
You'll also need to make methods get() and num() static to compile.
It's an instance (non-static) field, so you need an instance to reference it:
public static void main(String[] args) {
System.out.println(new Name().b);
}
Static methods can only access static properties. You could either make b static, or you can instead instantionalize Name:
public class Name{
int b = 100;
public void get(){
System.out.println(b);
}
public int num(){
return b;
}
public static void main(String[] args) {
new Name(args);
}
public Name(String[] args) {
System.out.println(b);
}

If I have more files in one project I need to make all fields static?

If I make for example one project. Inside with two class. For example: X and Y. I make them what I want, and I want to make a main method in Y. Only system.out.printlf the values in X and Y. But it writes that I need to make them static if I want to run this. I tried to make a new file with only the main class and inside the X Y values but it showed an error. What I missed?
you have missed object creation. Try X x = new X(); in your Y file. I would recommend to read some tutorials on Java, starting from here.
The main method is declared static
public static void main(String[] args) {}
Inside of main, it can only access static variables that exist in the enclosing class. You will see this for example with this bit of code:
public class X {
private int i = 5;
public static void main(String[] args) {
System.out.println(i);
}
}
To make the above work you need to declare i as static:
public class X {
private static int i = 5;
public static void main(String[] args) {
System.out.println(i);
}
}
A better way would be to do this:
public class X {
private int i = 5;
public X() {
System.out.println(i);
}
public static void main(String[] args) {
new X();
}
}
Static methods can only access static methods and other variables declared as static.
This article may also help you to understand what is going on here.
I'm guessing that's because everything happens inside the main method which is indeed static right? e.g.
public class C {
int X;
int Y; //or whatever other type
..
public static void main(String args[]) {
System.out.print( X ); //this won't work!
}
}
instead use this aprroach:
public class C {
int X;
int Y; //or whatever other type
..
public static void main(String args[]) {
C inst = new C();
System.out.print( c.X ); //this will work!
}
}
The main method is static and can only access static fields from the class. non static fields belong to an instance/object which you'd have to create:
public class X {
static int a = 0;
int b = 0;
public static void main(String[] args) {
System.out.println(a); // OK -> accesses static field
System.out.println(b); // compile error -> accesses instance field
X x = new X();
System.out.println(x.b); // OK -> accesses b on instance of X
}
}

Categories