Error calling a subclass method from another class - java

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

Related

How to call a constructor of child class in a main static method? (Java) [duplicate]

I wrote the below code to test the concept of classes and objects in Java.
public class ShowBike {
private class Bicycle {
public int gear = 0;
public Bicycle(int v) {
gear = v;
}
}
public static void main() {
Bicycle bike = new Bicycle(5);
System.out.println(bike.gear);
}
}
Why does this give me the below error in the compiling process?
ShowBike.java:12: non-static variable this cannot be referenced from a static context
Bicycle bike = new Bicycle(5);
^
Make ShowBike.Bicycle static.
public class ShowBike {
private static class Bicycle {
public int gear = 0;
public Bicycle(int v) {
gear = v;
}
}
public static void main() {
Bicycle bike = new Bicycle(5);
System.out.println(bike.gear);
}
}
In Java there are two types of nested classes: "Static nested class" and "Inner class". Without the static keyword it is an inner class and you will need an instance of ShowBike to access ShowBike.Bicycle:
ShowBike showBike = new ShowBike();
Bicycle bike = showBike.new Bicycle(5);
Static nested classes and normal (non-nested) classes are almost the same in functionality, it's just different ways to group things. However, when using static nested classes, you cannot put definitions of them in separated files, which will lead to a single file containing a lot of class definitions.
Bicycle is an inner class, so you need outer class instance to create inner class instance like :
ShowBike sBike = new ShowBike();
Bicycle bike = sBike.new Bicycle(5);
Or you can simply declare Bicycle class as static to make your current way work.
The main method cannot access a non-static member of its class.
By the way, classes should be named after nouns, not verbs. So a better way to do it is :
private class Bicycle {
public int gear = 0;
public Bicycle(int v) {
gear = v;
}
public void showGear() {
System.out.println(gear);
}
public static void main(String[] args) {
Bicycle bike = new Bicycle(6);
bike.showGear(); // Notice that the method is named after a verb
}
}
You need to create outer class object instate of inner class. or you need to make inner class as static. so for inner class no object required.
Your Bicycle class is not static, and therefore cannot be used in a non-static method. If you want to use it in the main method, change it to
private static class Bicycle

Anonymous class instantiation with definition - overwrite protected method

Lets assume I have class:
class A {
protected int x; // no public getter, setter
}
Now I want to extend class A, to overwrite 'x' variable. The answer would be:
public class SomeClass {
someMethod() {
A extendedClass = new MyExtension(5);
}
class MyExtension extends A {
public MyExtension(int x) {
super.x = x;
}
}
}
And my question: is there any possibility to do it without defining nested class separately? I mean something like this
someMethod() {
A extendedClass = new A() {
// here do something like super.x = 5;
}
}
I tried with Calling newly defined method from anonymous class but it won't let me instantiate A class. Also I dont want to use reflection.
I simpy dont want to define nested class just to overwrite one property. Origin of the problem is Spring-integration ImapMailReceiver, where I want to overwrite task scheduler. Like below:
final ImapMailReceiver imapMailReceiver = new ImapMailReceiver() {
super.setTaskScheduler(MYTASKSCHEDULERHERE);
}
Your new A() { ... } still is just defining a new class. Thus, you cannot simply put any statement between the curly brackets, only field, method and nested type declarations may go there, but constructors are not allowed. You may add an instance initializer instead:
A extendedClass = new A() {
{
x = 5;
}
}
Why to use nested or anonymous inner class?
We can do overriding and access the overrided variable as below.
public class SomeClass extends A{
int val;
void someMethod(int val) {
super.x = val;
}
public static void main(String[] args) {
SomeClass sc = new SomeClass();
System.out.println(sc.x); // output=10
sc.someMethod(20);
System.out.println(sc.x); // output=20
}
}
class A {
protected int x = 10; // no public getter, setter
}

Using Base Class Method Value In Inherited Classes Overridden Method

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

How to initialize a protected final variable in a child class of an abstract parent in Java?

I tried this:
class protectedfinal
{
static abstract class A
{
protected final Object a;
}
static class B extends A
{
{ a = new Integer(42); }
}
public static void main (String[] args)
{
B b = new B();
}
}
But I got this error:
protectedfinal.java:12: error: cannot assign a value to final variable a
{ a = new Integer(42); }
^
1 error
How to work around this problem?
Some people suggested here to use a constructor but this works only in some cases. It works for most objects but it is not possible to reference the object itself from within the constructor.
static abstract class X
{
protected final Object x;
X (Object x) { this.x = x; }
}
static class Y extends X
{
Y () { super (new Integer(42)); }
}
static class Z extends X
{
Z () { super (this); }
}
This is the error:
protectedfinal.java:28: error: cannot reference this before supertype constructor has been called
Z () { super (this); }
^
One could argue that it does not make much sense to store this kind of reference, because this exists already. That is right but this is a general problem which occurs with any use of this in the constructor. It is not possible to pass this to any other object to store it in the final variable.
static class Z extends X
{
Z () { super (new Any (this)); }
}
So how can I write an abstract class, which forces all child classes to have a final member which gets initialized in the child?
You have to initialize A.a in its constructor. Subclasses will use super() to pass initializer to A.a.
class protectedfinal {
static abstract class A {
protected final Object a;
protected A(Object a) {
this.a = a;
}
}
static class B extends A {
B() {
super(new Integer(42));
}
}
public static void main (String[] args) {
B b = new B();
}
}
You cannot use this until superclass constructors were called, because at this stage the object is not initialized, even Object constructor hasn't run at this point, therefore calling any instance methods would lead to unpredictable results.
In your case, you have to resolve circular reference with Z class in another way:
Z () { super (new Any (this)); }
Either use a non-final field or change class hierarchy. Your workaround with instance method super(new Any(a())); would not work for the same reason: you cannot call instance methods until superclass constructors were run.
In my personal oppinion, your problems hints towards a flaw in design.
But to answer your question. If absolutly necessary, you can change final fields in java using reflection.
And if everything fails, you can still utilize sun.misc.unsafe.
But I strongly discourage you from doing so, since it potentially kills your vm.
My work around so far is to use methods instead of final members:
class protectedfinal
{
static abstract class AA
{
protected abstract Object a();
}
static class BB extends AA
{
#Override
protected Object a() { return this; }
}
public static void main (String[] args)
{
AA a = new BB();
System.out.println (a.a());
}
}
But I would like to use final members, because I think accessing a final member is faster than calling a method. Is there any chance to implement it with final members?

How do I call a method from another class?

I am having problems accessing a method that is in a separate class, when I try to call it from my main class. This is the method
class RobotData
{
private int junctionRecorder(IRobot robot)
{
int[] juncX;
int[] juncY;
int[] arrived;
int[] junctions;
int i = 0;
i = junctions[0];
juncX[i] = robot.getLocationX();
juncY[i] = robot.getLocationY();
arrived[i] = robot.getHeading();
junctions[0]++;
return i;
}
}
and when I try to call it in my main class, using
public class Test
{
public void controlRobot(IRobot robot)
{
int recordjunction = junctionRecorder(robot);
//...
it comes up with this error
Test.java:7: cannot find symbol
symbol : method junctionRecorder
Can anyone help?
You have to make an instance of object to call its method (if it's not static):
public class Test
{
public void controlRobot(IRobot robot)
{
RobotData rd = new RobotData();
int recordjunction = rd.junctionRecorder(robot);
//...
Or something like this (I supose you wanted to do this):
public class Test
{
public void controlRobot(IRobot robot)
{
int recordjunction = robot.junctionRecorder(robot);
//...
But in this case class RobotData have to implement interface IRobot:
class RobotData implements IRobot
And also method junctionRecorder is private, you have to make it public.
Anyway, I think that you should first read about fundamentals (like objects, instances, creating them etc.) and be sure that you understand it.

Categories