I have written a small program in Java, a there is something I just do not understand.
Program that I have wrote has 3 classes kingClass, masterClass, and workClass. workClass extends masterClass.
Program: in the main class (kingClass) I have declared masterClass and workClass, and with the masterClass I have given values to variables x, and y. In the end of kingClass I have called a addNum function that sum two numbers from the masterClass.
Now the problem: I expected when I run the program that it will give me a sum of two numbers I have given with input, not the sum of number that I have given value in constructor.
How can write this program so that addNum returns the value of the sum of number I have enterd.
Sorry for bad english, Thank you..
kingClass
public class kingClass
{
public static void main(String[] args)
{
masterClass mClass=new masterClass();
mClass.setX(10);
System.out.println(mClass.getX());
mClass.setY(5);
System.out.println(mClass.getY());
workClass wClass = new workClass();
System.out.println(wClass.addNum());
}
}
masterClass
public class masterClass
{
private int x;
private int y;
masterClass()
{
x=0;
y=0;
}
public void setX(int a) {x=a;}
public void setY(int a) {y=a;}
public int getX() {return x;}
public int getY() {return y;}
}
workClass
public class workClass extends masterClass
{
int num=getX()+getY();
public int addNum() {return num;}
}
The following two statements:
masterClass mClass=new masterClass();
workClass wClass = new workClass();
create two objects that are completely independent from one another. When you modify one, this has no effect on the other.
Did you mean:
public static void main(String[] args)
{
workClass wClass = new workClass();
wClass.setX(10);
System.out.println(wClass.getX());
wClass.setY(5);
System.out.println(wClass.getY());
System.out.println(wClass.addNum());
}
?
The fact that workClass extends masterClass enables you to use masterClass's public methods on an instance of workClass.
There is also a bug in your addNum() method:
public class workClass extends masterClass
{
public int addNum() {return getX() + getY();}
}
Your current implementation adds the numbers together at construction time, disregarding any changes made to x and y post-construction.
You don't assign the value to x and y when you create the object of WorkClass. Extending a class just means that the data members are inherited. It doesn't mean that all the objects that you create of the base class will automatically be copied to the derived class when you create a new object of derived class.
You've assign values to x and y on the mClass instance, not on wClass, so num will always be zero.
You have two errors there:
First, you are setting the values on one object (first masterClass instance), and adding values from another one (the workClass, which is a different object instance).
Second: Your num attribute will be set at the creating time, and not reevaluated later. This is because you have defined it assigning the value.
How to fix it:
public class kingClass
{
public static void main(String[] args)
{
//fix the first error: set and calculate at the very same object
workClass mClass=new workClass();
mClass.setX(10);
System.out.println(mClass.getX());
mClass.setY(5);
System.out.println(mClass.getY());
System.out.println(mClass.addNum());
}
}
And:
public class workClass extends masterClass {
public int addNum() {
//fix the second point: don't save the value, but recalc every time you need with the actual current value of x and y
return getX()+getY();
}
}
mClass and wClass are 2 different objects.
Also the addition happens during object creation so 10 and 5 don't get added.
So you need to make modifications to kingClass and also workClass.
class kingClass
{
public static void main(String[] args)
{
workClass wClass=new workClass();
wClass.setX(10);
System.out.println(wClass.getX());
wClass.setY(5);
System.out.println(wClass.getY());
System.out.println(wClass.addNum());
}
}
class workClass extends masterClass
{
public int addNum() {return getX()+getY();}
}
Related
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;
For example:
In Class One
int killcount = 0;
In Class Two
killcount = 5;
All I want to do I get the variable from one class to another class. How would I do that?
Before trying to work with Bukkit I'd recommend you to get some Java experience first. That's not meant as an insult, but it can get quite confusing if you do it the other way round. Anyways, if you still want to know the answer to your question:
You'll have to create a getter & setter for your "killcount" variable.
class Xyz {
private int killcount;
public void setKillcount(int killcount) {
this.killcount = killcount;
}
public int getKillcount() {
return this.killcount;
}
}
Of course this is a simplified version without checks, but if you want to access the variable from a different class you can create an instance and use the methods to modify it.
public void someMethod() {
Xyz instance = new Xyz();
instance.setKillcount(instance.getKillcount() + 1);
//this would increase the current killcount by one.
}
Keep in mind that you'll have to use the same instance of the class if you want to keep your values, as creating a new one will reset them to default. Therefore, you might want to define it as a private variable too.
Consider the examples
public class Test {
public int x = 0;
}
This variable x can be accessed in another class like
public class Test2 {
public void method() {
int y = new Test().x;
// Test.x (if the variable is declared static)
}
}
Ideally, the instance variables are made private and getter methods are exposed to access them
public class Test {
private int x = "test";
public int getX() {
return x;
}
public void setX(int y) {
x = y;
}
}
i have a question regarding default constructors in java.
as much as i have read about constructors in java, a default constructor initializes all instance variables to their default values. but what if we define a constructor for a class, then how come variables are initialized to their default values if we want them to ?
suppose i have 2 files
a.java
public class a
{
int x;
public a(int z)
{
if(z > 0)
{
x = z;
}
}
public void get()
{
System.out.println(x);
}
}
and b.java
public class b
{
public static void main(String[] args)
{
a obj = new a(-4);
obj.get();
}
}
now here condition (z>0) fails, so x is initialized to zero. but what exactly does this as their is no default constructor in class a.
Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type.
Source
That means that the compiler will do that for you when you build the program.
In your a class (renamed A below to follow conventions) as you have written it, there is no default constructor. A default constructor for a class is a constructor which is public and has no arguments.
With the code you have written, this will fail:
A a = new A();
As soon as you declare another constructor in a class, there is no default constructor anymore.
As to instance variables, if you do not initialize them explicitly, they are set to default values. That is:
public class A
{
private int x;
public int getX()
{
return x;
}
}
if you do:
final A a = new A();
System.out.println(a.getX());
this will print out 0. The class above is exactly equivalent to:
public class A
{
private int x /* = 0 -- default value for uninitialized int instance variables */;
// redundant
public A()
{
}
public int getX()
{
return x;
}
}
When you declare a variable in java, it's by default initialized as it's default value.
For the primitive types is that 0 (or it's equivalent), for Objects is that null
So in your example has x initialy the value 0 and you never overwrite it.
In java if we dont define any constructor, it takes its self a default constructor which will have default values.while we creating object we intialize values to the constructor.
public class Car{
int numOfWheels;
public Car(int numOfWheels){ //created constructor//
this.numOfWheels=numOfwheels;
}
}
public static void main(string[]args){
Car skoda = new Car(4);
} *//initialized value to the object using constructor in parenthesis//*
public class a
{
int x;
public a(int z)
{
//as we know that every class base class is Object class this constructor first statement is super(); means compiler automatically add this statement that call object class default constructor and initialize default values
if(z > 0)
{
x = z;
}
}
public void get()
{
System.out.println(x);
}
}
public class a
{
int x;
public a(int z)
{
/*As we know that every class base class is Object.....
compiler automatically add super(); that call Object class default constructor
that initialize the value of instance variable */
if(z > 0)
{
x = z;
}
}
public void get()
{
System.out.println(x);
}
}
public class b
{
public static void main(String[] args)
{
a obj = new a(-4);
obj.get();
}
}
//other example is below
/*class A
{
public A()
{
System.out.println("Arjun Singh Rawat and Ashish Chinaliya");
}
}
class B extends A
{
public B()
{
//compiler automatically add super();
}
}
class calling
{
public static void main(String arg[])
{
B bb=new B();
}
}*/
thanks...
public class Demo {
static int a;
Demo(int b )
{
System.out.println(" Constructor");
}
public static int func()
{
System.out.println(a);
return 1;
}
public static void main( String args[])
{
new Demo(func());
}
}
Output
0
Constructor
It's not the default constructor that initializes our fields to their default values ,
In this program, the static field a is being initialized to 0 even though there is no default constructor
added by the compiler. Also it's being initialized to 0 before a constructor being called .
i'm relativly new to java and experimantating a bit with javafx
i want to change a variable from class A while using a method from class B
Main: thats the main class, it contains all the needed stuff(shows the primaryStage etc) it does have an constructor, so its not creating an actual "main-object"
public class Main extends Application {
Sub sub = new Sub();
int a;
// stuff
public void aMethod() {
sub.subMethod();
}
}
Sub: this class solely surpose is to change the variable a, it does not contain a constructor to create a "sub-object"
public class Sub {
//stuff
subMethod(){
int a = 5;
}
if i put the line Main main; in the Sub class, the program will give me a nullpointer exception, if i'm calling the subMethod().
ok...i guess cause i didnt actually create the main object... so far so good.
BUT... if i put in the line Main main = new Main(); the program wont even start giving me an "exception while running application" error
the strange thing though is, if i put the line Main main = new Main(); in the subMethod...
subMethod(){
Main main = new Main();
int a = 5;
}
...the damn thing actually works...(well its slow, guess because with every calling of the method its creating a new object)
why is that so?
and how is it done correctly? :)
(using methods of other classes to "overwrite" variables)
regards
Red
You should not create more than one instance of Main in your program. Probably Main is not the best place to store mutable state (class members), but if you want that, you need to pass the instance of Main to subMethod (and make a public, or provide a public setter method):
public class Main extends Application {
Sub sub = new Sub();
public int a;
// stuff
public void aMethod() {
sub.subMethod(this);
}
}
public class Sub {
//stuff
subMethod(Main main){
main.a = 5;
}
So you want a method to change the value of another class's fields. There are a few ways to do this. If you have this class
public Class A {
private int a;
...
public void setA(int a) {
this.a = a;
}
}
You can do something like this
public Class B {
private static A instance;
....
public static void setA(int a) {
instance.setA(a);
}
}
Or you can take the A in as a parameter to the set method
public Class B {
...
public static void setA(A a, int val) {
a.setA(val);
}
}
If you want direct access to the fields on A you have to make them public (this is usually not what you want to do as it gives complete access rather than just giving just the access the other classes require)
Public Class A {
public int a;
...
}
Then you can do
Public Class B {
...
public static void setVal(A a, int val) {
a.a = val;
}
}
Also if you don't have the method setA in B as static you'll have to call it on an instance of B like
B b = new B();
b.setA(a, val);
Where as if it's static you call it on the class B
B.setA(a, val);
I have a Java assessment that gets marked by a robot. Whenever I upload my assignment it shows a screen like this.
A good object-oriented design places each method into the most appropriate
class. The most appropriate class for a method should be the same class as
the data fields that that method needs to access. If you don't place a method
into the right class, then this will most likely increase the amount of
communication that is required between your classes.
The score below measures the amount of communication between your classes. A
lower score is better.
19 method invocations between classes
7 arguments passed between classes
15 results returned between classes
Amount of communication = invocations + 2*inputs + 2*outputs = 63
Now what exactly does "method invocations between classes", "arguments passed between classes" and "results returned between classes" mean?
Method invocations between classes
As your class contains their own methods if you want to call the method from another class you have to use an instance of this class.
For example :
class A{
public void methodA(){
}
}
class B{
public void methodB(){
}
}
If I want to call methodA() from the class B I must use this:
public void methodB(){
A a = new A();
a.methodA(); // method invocation between classes
}
Argument passed between classes
This time methodA() will need an argument, and B as a field which could be used as argument.
class A{
public void methodA(int argument){
}
}
class B{
private int fieldB = 42;
public void methodB(){
}
}
To call methodA() from B you will pass an argument from a class to another.
public void methodB(){
A a= new A();
a.methodA(fieldB); //Argument passed between classes
}
Results returned between classes
And now methodA() returns a result this is the code.
class A{
public int methodA(){
return 42;
}
}
class B{
private int fieldB;
public void methodB(){
}
}
To use/handle the returned value of the methodA() from the class B you'll have to do this:
public void methodB(){
A a= new A();
fieldB = a.methodA(); //Result returned between classes
}
I'd have to say:
method invocations between classes
Suppose you have classes X and Y. This would be any time class X calls some method on class Y.
e.g.,
class Y
{
public void foo() { }
}
class X
{
public void someMethod()
{
Y y = new Y();
y.foo();
}
}
arguments passed between classes
Could possibly mean one of two things.
Either you are accessing a field of another class directly.
class Y
{
public int number;
}
class X
{
public void someMethod()
{
Y y = new Y();
int yNum = y.number;
}
}
Or a method was called where arguments are supplied. (most likely case)
class Y
{
public void foo(int arg) { }
}
class X
{
public void someMethod()
{
Y y = new Y();
y.foo(56);
}
}
results returned between classes
Received a value from a method of another class that returned a value. e.g., getters or other methods.
class Y
{
public int foo() { return 42; }
private int number;
public int getNumber() { return number; }
}
class X
{
public void someMethod()
{
Y y = new Y();
int yFoo = y.foo();
int yNumber = y.getNumber();
}
}