Define constructor in Java - 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);
}
}

Related

How to change static variable inside in a class by a method

I have three classes:
Class One
public class One {
private static Two object;
public static void set_up(Two object) {
int y = object.get();
System.out.println(y);
}
public static void prn () {
System.out.println(object.get());
}
}
Class Two
public class Two {
private int x;
public int get() {
return x;
}
Two(int n){
x = n;
}
}
Class Three
public class Three {
public static void main( String[] argv ) {
One st = new One();
Two two = new Two(2);
st.set_up(two);
st.prn();
}
}
I want to change the static variable object in class Two by method set_up(Two object).
The problem is that static variable inside the class has the same name as the arguments in the method. How can I modify set_up(Two object) so I copy values from given argument to static object?
You can qualify it by using the class' name:
public static void set_up(Two object) {
One.object = object;
}

How to change an objects values through methods in a different class Java

So I'm trying to edit an object's x value from a method in a different class. The real reason I'm doing this is far more complicated but I just wanted to simplify things.
I am creating a game and I want the object that belongs to the first Class to be updated throughout the game. However when I try to update it, it appears in the other class however as soon as scope is returned to the first class the x value remains 0.
I have been struggling with this for hours...
public class first {
private second Second;
public void view() {
System.out.println(this.Second.x);
}
public void newObj() {
Second = new second();
}
public void changeObj() {
Second.changeX(4);
Second = Second.getSecond();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
first First = new first();
First.newObj();
First.changeObj();
First.view();
}
}
public class second {
public static int x=0;
public second getSecond() {
return this;
}
public second(){
x=0;
}
public static void changeX(int x) {
x = x;
System.out.println(x);
}
public int getX() {
return x;
}
}
You're encountering this because of the way the assignment is done:
x=x;
Just doing this should trigger a warning message "The assignment to variable x has no effect". This is because you're not referring to the static variable x but the argument itself.
Each non-static variable exists in the context of an object. In this case x is static so the usage of this.x = x; in a static context is not possible either. The correct approach is
Second.x = x;

error in calling a method in the same class

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

Visibility of inner class variables

I have a code-
public class Hello
{
void create()
{
Inner obj=new Inner();
obj.r=100; //Able to access private variable x
obj.display(); //displays 100
}
class Inner
{
private int r=45;
void display()
{
System.out.println("r is : "+r);
}
}
public static void main(String[] args)
{
Hello ob=new Hello();
ob.create();
}
}
In the above code,by creating an instance of the inner class,we are able to access the private variable defined in that class.But this is not in the case of inheritance.Why it is so?For e.g.,in this code-
class One
{
private int x;
void getData()
{
x=10;
}
void display()
{
System.out.println("x is : "+x);
}
}
class Two extends One
{
int y;
void putData()
{
One o=new One();
o.x=13; //Error
}
}
public class File
{
public static void main(String[] args)
{
Two to=new Two();
to.putData();
}
}
What is the exact reason behind it?Thanks in advance...
See the Java Language Specification.
Otherwise, if the member or constructor is declared private, then access is permitted if and only if it occurs within the body of the top level class (ยง7.6) that encloses the declaration of the member or constructor.
Meaning that a top-level class can access the private members of it's nested classes.
Or said another way: Private means private to the top-level class and all it's nested classes, not private to the nested class itself.

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