Base Class;
import java.util.Random;
public class Animal
{
public void move()
{
int value = 0;
System.out.println("Move");
Random rand = new Random();
value = rand.nextInt(2)+1;
}
}
Inherited Class;
public class Cat extends Animal
{
public void moveCat()
{
super.move();
System.out.println("Move Cat");
}
public static void main(String[] args)
{
Cat test = new Cat();
test.moveCat();
}
}
I Am trying to use a value of the base class animals method move in the override method moveCat. Why cant I use the value "value" in moveCat from Cat.
For Example;
public void moveDoodle()
{
super.move();
System.out.println("Move Doodle");
if(value == 1)
{
System.out.println("Value from base");
}
}
If I am grabbing the content from the base method why can't I also use the values. If its not possible what should I be doing instead in order to get the values I need.
That's because value is in the local scope of the method move() of your base(Animal) class and that is why its not inherited. Only the instance variables will be inherited(provided they are not private). Thus, you need to make value an instance variable for you to be able to inherit it in your base(Animal) class.
int value = 0;
public void move()
{
// int value = 0;
System.out.println("Move");
Random rand = new Random();
value = rand.nextInt(2)+1;
}
Note: I can see that you've inherited the Animal class but have not overriden any method, contrary to what was suggested in the question title.
because value is a local variable to method move(). Local variables are not inherited. Create the variable as instance variable.
By the way, if you are trying to override to move() method, you need to keep the same method signature.
import java.util.Random;
public class Animal {
int value = 0;
public void move() {
System.out.println("Move");
Random rand = new Random();
value = rand.nextInt(2) + 1;
}
}
Your Cat class
public class Cat extends Animal {
public void moveCat() {
super.move();
System.out.println("Move Cat");
}
public static void main(String[] args) {
Cat test = new Cat();
test.moveCat();
System.out.println(test.value);
}
}
With your implementation, the value variable is of local scope. It is accessible only within the move method and the outer world doesn't know about this.
You will need to declare this variable at the instance scope in order to make it accessible at the class level. You will also need to declare the access modifier for this so that the inheriting class know about it.
The following will work.
protected int value = 0;
public void move()
{
System.out.println("Move");
Random rand = new Random();
value = rand.nextInt(2)+1;
}
Related
I want to clarify beforehand that I am only interested in programming from a hobbyist perspective and have no education regarding programming nor do I have any professional experience.
I am trying to figure out how to affect the instance fields of one class with the instance fields of another. Here is an example of what I'm trying to figure out:
//Main Class
class Main
{
public static void main(String[] args)
{
Class1 instance1 = new Class1(1);
Class2 instance2 = new Class2(1);
}
public void method1()
{
// code to add the class1 instance field value class1Num1 to Class2 instance field value class2Num1
// at least cobine the two values in one variable that is usable in Main
}
}
//Class1
class Class1
{
int class1Num1;
public Class1(int num1)
{
class1Num1 = num1;
}
}
//Class2
class Class2
{
int class2Num1;
public Class2(int num1)
{
class2Num1 = num1;
}
}
Ultimately I want to know how I could get class2Num1 and add it to class1Num1 in the Main class. I mean want to change the value of class1Num1 via a method so that later in my program when class1Num1 is referenced, the value returned is 2 (class1Num1 +class2Num1). How would I write a method to do that and what class or classes would I have to write this in? This may be an incredibly simple task I realize but I can't seem to figure this out.
Based on responses it look as if getter and setter methods are the way to go however, based on the examples I have seen so far it looks as though instance1 and instance2 are having to be passed as arguments in the Main class method that combines the two numbers. Is there a way that I could write a method so that it targets the instance that calls the method? Here is an example:
//this method is being called in Main
instance1.method(int class2){
int a = getClass1Num1();
// ^ how could I target the instance calling this method here?
//
int b = class2.getClass2num1();
int c = a +b;
}
It's better to use private fields and getter and setter methods
Class1 is as follows
public class Class1 {
//fields
private int class1Num1;
//getter
public int getClass1Num1() {
return class1Num1;
}
//setter
public void setClass1Num1(int class1Num1) {
this.class1Num1 = class1Num1;
}
}
Class2 is as follows
public class Class2 {
//fields
private int class2Num1;
//getter
public int getClass2Num1() {
return class2Num1;
}
//setter
public void setClass2Num1(int class2Num1) {
this.class2Num1 = class2Num1;
}
}
Main Class is as follows
public class Main {
public static void main(String[] args) {
//Set class1Num1
Class1 instance1 = new Class1();
instance1.setClass1Num1(1);
//Set class2Num1
Class2 instance2 = new Class2();
instance2.setClass2Num1(1);
//add class1Num1 + class2Num1
int sum = instance1.getClass1Num1() + instance2.getClass2Num1();
//Set sum into class1Num1 of instance1
instance1.setClass1Num1(sum);
//Printing class1Num1 (2)
System.out.println(instance1.getClass1Num1());
}
}
a good object oriented way to do that would be to include a getter method to return the instance variable of your classes. Eg you should add a method like this to your Class1 and Class2 :
public int getInstanceVar() {
return class1Num1; // Or class2Num1 in Class2
}
Then in your main class you can call this method from your newly created Class1 // Class2 objects, eg :
int result = instance1.getInstanceVar() + instance2.getInstanceVar();
public class Main {
public static void main(String[] args) {
Object[] array = new Object[1];
Piece piece = new Piece();
array[0] = piece;
array[0].move();
}
}
class Piece{
public void move(){
System.out.println("hello");
}
}
Line 6 doesn't not work and I am not sure why. Shouldn't array[0] give me piece and piece.move() call the method in the class?
You are casting Piece as Object when you add it to the Object array.
Try this:
public class Main {
public static void main(String[] args) {
Piece[] array = new Piece[1];
Piece piece = new Piece();
array[0] = piece;
array[0].move();
}
}
class Piece{
public void move(){
System.out.println("hello");
}
}
It's because on line array[0] = piece; you are assigning Piece object to Object which is valid because Object is the parent class of all.
But when you do array[0].move(); you are trying to call the move() method from reference of Object class.
This is not possible because move() method is not declared in Object class.
Thus you need to cast like below:
((Piece)array[0]).move();
When you store a Piece as Object the compiler does not know anymore that it is a Piece. You have to explicitly tell it (cast it ((Piece)array[0]).move();).
Alternatively store objects in Piece[] array.
I assume the real motivation is storing different pieces types. In this case they all have to have the same base type. This can be achieved by having all pieces types extend the same base class, or implement a common interface:
public class Main {
public static void main(String[] args) {
Movable[] array = new Movable[2];
APiece aPiece = new APiece();
BPiece bPiece = new BPiece();
array[0] = aPiece;
array[0].move();
array[1] = bPiece;
array[1].move();
}
}
interface Movable {
void move();
}
class APiece implements Movable{
#Override
public void move(){
System.out.println("APiece moved ");
}
}
class BPiece implements Movable{
#Override
public void move(){
System.out.println("BPiece moved ");
}
}
SO,letsay we have a bicycle superclass with cadence 0 and 3 subclasses.I want the "trotineta" sbuclass to have cadence 5 while the other 2 subclasses cadence remains 0.
Why isnt this working?
class Trotineta extends Bicycle{
Bicycle.cadence = 5;
}
You haven't shown the definition of Bicycle.cadence, but based on the syntax, I'm assuming it's a static member. If you change a static member of the base class, all instances of all sub-classes will be affected by this change, since a static member has a single value for all instances of the class.
Now, if cadence wouldn't be static, you can give it a different value in the constructor of Trotineta (assuming the sub-class has access to that member).
public Trotineta ()
{
cadence = 5;
}
This would be somewhat wasteful, though, since each instance of Bicycle would have its own cadence member.
You can create getter and setter or just use word super
public class TestONE extends TestTWO {
{
super.gg = 4;
}
public static void main(String[] args) {
System.err.println(new TestONE().gg);
}
}
class TestTWO {
static int gg = 0;
}
or
public class TestONE extends TestTWO {
public static void main(String[] args) {
TestONE.setGg(5);
System.err.println(new TestTWO().gg);
}
}
class TestTWO {
protected static int gg = 0;
public static int getGg() {
return gg;
}
public static void setGg(int gg) {
TestTWO.gg = gg;
}
}
class Bicycle{
int cadence = 0;
/* since no access modifier is mentioned, by default cadence becomes
package private ie; it cannot be accessed outside the package
in which it is defined now*/
}
class Trotineta extends Bicycle{
Bicycle.cadence = 5;
/* you cannot do this as cadence is not a static
attribute of class Bicycle*/
}
// Below is one of the possible solutions
class Trotineta extends Bicycle{
/*below code can also be written in a method but not outside as you have
written in your example code*/
{
this.cadence = 5;
//here 'this' is the current instance of Trotineta
}
}
I have three classes:
public class BikeSystem {
static Bicycle[] bicycleArray = new Bicycle[100];
static int currentBikes = 0;
public static void addUnicycle() {
bicycleArray[currentBikes] = new Unicycle();
currentBikes++;
}
public static void addUniWheel() {
for (int i=0; i < currentBikes; i++) {
if (bicycleArray[i] instanceof Unicycle)
bicycleArray[i].addWheel();
}
}
}
public class Bicycle {
// some variables
}
public class Unicycle extends Bicycle {
private int wheels;
public boolean addWheel() {
wheels++;
return true;
}
}
However, I keep getting a "cannot find symbol" error when I try to call the bicycleArray[i].addWheel() method in my BikeSystem class. How do I get around this?
You should explicitly state that you are operating on an instance of Unicycle in order to gain access to the addWheel() method. You can do this by casting.
((Unicycle) bicycleArray[i]).addWheel();
Obviously, if you try to cast to Unicycle on an instance of an object that is not a Unicycle or a further subclass, you will get a ClassCastException
bicycleArray is declared as an array of Bicycle and there is no addWheel method defined by it.
You're trying something similar as:
Bicycle bicycle = new Bicycle();
bicycle = new Unicycle();
bicycle.addWheel(); // err
I'm trying to call some integers into a class from a method within another class
public class Variables
{
public void vary()
{
int DSpr
}
}
public class BattleCalc
{
public static void main(String[] args)
{
Variables v = new Variables();
v.vary();
Scanner spr = new Scanner(System.in);
DSpr = Integer.parseInt(spr.nextLine()); //This line here
}
}
This is my code so far, but on DSpr = Integer.parseInt... eclipse gives me an error "DSpr cannot be resolved". Why is it not calling DSpr from Variables ?
" call some integers into a class from a method within another class" makes no sense to me. Variables in a method are local to that method ONLY
I think what you want to do is something like this
public class Variables
{
...
public int DSpr;
}
...
v.DSpr = Integer.parseInt(spr.nextLine());
i.e Make DSpr a public member variable of the Variables class.
It is recommended that you instead make it a private variable and write setter-getter methods for users outside the class to use it.
Try this: in order to access a variable at another class, it must be declared as class variable.
At your Class Variables:
public class Variables{
int DSpr;
public void vary(){
//do assignment here or operation, if you want to create a method
DSpr = 0;
}
}
Then call it on your main class.
int DSpr is declared locally within vary() method and hence can't be accessed outside of that method. even in it's enclosing class Variables
To access a variable in another class, it should be defined as instance field. (or class variable / static variable)
public class Variables
{
public int DSpr;
// OR
// public static int DSpr;
public void vary()
{
}
}
Now, in BattleCalc class you can access as following:
Variables v = new Variables();
v.DSpr = Integer.parseInt(spr.nextLine());
// OR
// Variables.DSpr = Integer.parseInt(spr.nextLine());
here your DSpr variable scope is limited to this method only:
public void vary()
{
int DSpr
}
so it can not be accessed anywhere else.
if you are using elsewhere you need to re-declare like:
int DSpr = Integer.parseInt(spr.nextLine());
You want to assign a value to DSpr from altogether another class. You should declare DSpr as member variable in Variable class and assign it by calling setter in that class.
Your code will be like this.
public class Variables
{
private int DSpr;
public void setDSPR(int DSpr)
{
this.DSpr=DSpr;
}
}
public class BattleCalc
{
public static void main(String[] args)
{
Variables v = new Variables();
Scanner spr = new Scanner(System.in);
try {
v.setDSPT(Integer.parseInt(spr.nextLine())); //This line here
} catch(NumberFormatException ex) {
System.out.print("Invalid Input.!")
}
}
}
Try this..
import java.io.*;
import java.util.*;
class Variables
{
public void vary()
{
int DSpr;
}
}
public class BattleCalc
{
public static void main(String[] args)
{
Variables v = new Variables();
v.vary();
Scanner spr = new Scanner(System.in);
int DSpr = Integer.parseInt(spr.nextLine()); //This line here
}
}
Yes You should get errors in above code, Here is my solution
I assume you want to change the variable value in vary(). But I am not sure the usage of this since you are not using the changed value in BattleCalc.
So get and set the integer variable you can use getters and sertters but here I will do minimum modifications to your code to make it easy to understand (so I am not using getters and setters here although it is the ideal way of doing)
public class Variables {
public int DSpr;
public void vary() {
// Change the value of DSpr
DSpr = 10;
}
}
public class BattleCalc {
public static void main(String[] args) {
Variables v = new Variables();
v.vary();
Scanner spr = new Scanner(System.in);
v.DSpr = Integer.parseInt(spr.nextLine()); //This line here
}
}