I am trying to do simple encapsulation program. The source has given below.
package encap;
public class Encap
{
public static void main(String[] args)
{
NewClass1 call = new NewClass1(3);
call.PrintNumber();
}
}
package encap;
public class NewClass1
{
private int numberNewClass1;
NewClass call = new NewClass(getNumberNewClass1());
public NewClass1(int number)
{
setNumberNewClass1(number);
}
public void PrintNumber()
{
// NewClass call = new NewClass(getNumberNewClass1());
System.out.println("NewClass1");
System.out.println(getNumberNewClass1());
System.out.println("NewClass");
System.out.println(call.getNumber());
}
public int getNumberNewClass1()
{
return numberNewClass1;
}
public void setNumberNewClass1(int numberNewClass1)
{
this.numberNewClass1 = numberNewClass1;
}
}
package encap;
public class NewClass
{
private int number;
public NewClass(int number)
{
setNumber(number);
}
public int getNumber()
{
return number;
}
public void setNumber(int number)
{
this.number = number;
}
}
During creating an object of Newclass1 i am giving value 3, as my knowledge that should be set at the private variable numberNewClass1 of Newclass1 cause i have called the setNumberNewClass1 within the NewClass1 Constructor.
Then i have created another object "call" globally of "NewClass" by giving getNumberNewClass1() method as constructor parameter of NewClass.
Now my problem is when i am calling the the getNumber() method of NewClass by call object within the PrintNumber() method in NewClass1, then it is returning 0. But if i create the object within
PrintNumber() method, then it is returning the value that was sent. The PrintNumber() method has called in class Encap.
Now my question is if the object crated Globally then the private variable of NewClass is not being initialized but if it is created locally then the private variable is getting value, why?
The issue is the order of initialization; first the numberNewClass1 field is initialized with 0 and then call is constructed (with that 0) – Here
private int numberNewClass1;
NewClass call = new NewClass(getNumberNewClass1()); //<-- currently 0.
You could move the initialization of call into the constructor of NewClass1 which will resolve your issue. Something like,
private int numberNewClass1;
private NewClass call;
public NewClass1(int number)
{
setNumberNewClass1(number);
call = new NewClass(number); //<-- now it is safe to call
// getNumberNewClass1(), but
// we know it is "number".
}
the instance-variable call in NewClass1 is initialized before the constructor has been executed, therefore the value which you pass in your main method never reaches call within NewClass1
Related
I'm trying to call a method from within another method. I'm understanding this simply enough, until one of those methods needs a variable carried through, and then nothing I try works.
I know that I could do this in one method, but my coursework needs me to lay it out in such a way. Why doesn't this work?
public class test2 {
public static void testMethod() {
int randomNumber = 1;
}
public static void anotherTestMethod(int randomNumber) {
System.out.println(randomNumber);
}
public static void main(String[] args) {
anotherTestMethod();
}
}
You are calling a method that has an int parameter in its signature. You should pass that parameter when calling the method. I think you are trying to use a global variable, in that case, you should declare it outside any method, as a part of the class.
public class test2 {
public static int testMethod() {
int randomNumber = 1;
return randomNumber;
}
public static void anotherTestMethod() {
System.out.println(testMethod());
}
public static void main(String[] args) {
anotherTestMethod();
}
}
When I've Created the subclass Alieni from the Settore class I get the error "Implicit super constructor Settore() is undefined. must explicitly invoke another constructor", i've looked similar questions and the answer given was to put a default constructor in my Settore class, i've done it and still get the same error
public class Settore {
private Nome settoreNome;
private char letteraX;
private final int coordinataX;
private final int coordinataY;
private int giocatoriPresenti;
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public int getGiocatoriPresenti() {
return giocatoriPresenti;
}
public void setGiocatoriPresenti(int giocatoriPresenti) {
this.giocatoriPresenti = giocatoriPresenti;
}
public char getLetteraX() {
return letteraX;
}
public void setLetteraX(char letteraX){
this.letteraX = letteraX;
}
public Settore (){}//suggestion given, still doesn't fix the problem, it just makes it worse
public Settore (int coordinataX, int coordinataY){
char myChar =letteraX;
int i=(int)myChar;
this.coordinataX=i-97;
this.coordinataY=coordinataY-1;
}
public int getX(){
return coordinataX;
}
public int getY(){
return coordinataY;
}
public Nome getSettoreNome() {
return settoreNome;
}
public void setSettoreNome(Nome settoreNome) {
this.settoreNome = settoreNome;
}
}
public enum Nome {
SICURO, PERICOLOSO, SCIALUPPA, ALIENI, UMANI
}
public class Alieni extends Settore {
public Alieni() {//this is where i get the error Implicit super constructor Settore() is undefined. must explicitly invoke another constructor
setSettoreNome(Nome.ALIENI);
}
}
It shows error even when you add a default constructor, bcoz the final variables you declared should have some value.They should be assigned values in the default constructor as below:
public Settore (){
coordinataX=5;
coordinataY=22;
}
Another way, if you want to use the parameterized constructor you have declared:
public Alieni()
{
super(5,6); //call to super class constructor
setSettoreNome(Nome.ALIENI);
}
You needed to add a default constructor because you need to initialize coordinataX and coordinataY:
public Settore(){
coordinataX=1;
coordinataY=2;
}
Otherwise the compiler will complain that these may not be initialized because a final member variable needs to be initialized at the declaration or in the constructor.
Put simply, I have an abstract class containing several variables and methods. Other classes extend this abstract class, yet when I try to read the private variable in the abstract class by calling getter methods inside the abstract class, it returns null as the value of the variable.
public class JavaApplication {
public static void main(String[] args) {
NewClass1 n1 = new NewClass1();
NewClass2 n2 = new NewClass2();
n1.setVar("hello");
n2.print();
}
}
public class NewClass1 {
public String firstWord;
public void setVar(String var) {
firstWord = var;
}
public String getVar () {
return firstWord;
}
}
public class NewClass2 extends NewClass1{
public void print() {
System.out.println(makeCall());
}
public String makeCall() {
return getVar();
}
}
Still prints out null.
Until the String is initialized, it will be null. You should probably have a constructor in the abstract class to set it.
public abstract class Command
{
String firstWord; // = null
protected Command(){}
protected Command( String w )
{
firstWord = w;
}
//...
}
public class Open extends Command
{
public Open()
{
this( "your text" );
}
public Open( String w )
{
super( w );
}
// ...
}
If you need to modify the firstWord string everytime execute() is called then it may not be necessary to use a constructor with a String parameter (I added a default constructor above). However, if you do it this way then either
You must make sure setFirstWord() is called before getFirstWord(), or,
Handle the case when getFirstWord() returns null. This could be by simply using a default value (maybe determined by each subclass) or something else, like failing to execute.
As I do not know all the details of your implementation I cannot tell you further information.
If I were to do something such as:
public class Game
{
private boolean RUNNING = true;
Game()
{
}
public static void main(String[] args)
{
Game game = new Game();
}
}
At what point in time would RUNNING = true?
edit: for clarity, at what point in the program would running be set to true. ex: Before the constructor, after the constructor, etc.
It will be set to true before the constructor. You can use it in the constructor as true.
This code explains itself:
public class SuperClass
{
String superField = getString("superField");
public SuperClass()
{
System.out.println("SuperClass()");
}
public static String getString(String fieldName)
{
System.out.println(fieldName + " is set");
return "";
}
public static void main(String[] args)
{
new ChildClass();
}
}
class ChildClass extends SuperClass
{
String childField = getString("childField");
public ChildClass()
{
System.out.println("ChildClass()");
}
}
OUTPUT:
superField is set
SuperClass()
childField is set
ChildClass()
When the constructor is called using the new operator all non-static members of the class are initialized before the code inside the constructor is executed. You can use the debugger and step into that call and see where it goes first. Static members are initialized when the class is loaded and for the first time accessed (see this question for more detailed info about static members).
private boolean RUNNING = true;
Game() {
}
is exactly the same as
private boolean RUNNING;
Game() {
RUNNING = true;
}
Actually, the comiler will move the initialization at the beginning of the constructor. The value will then be set when instantiating an object of that class.
When you try to use local variables which not manually initialized, you will get a compile time error.
public static void main(String args[]){
int a;
System.out.pritnln(a); //error
}
But it's not the case with instance variables. This itself shows that they are ready for usage before the constructor even.
public class Example{
private int a;
public Example(){
System.out.println(a); //No error
}
public int getA(){
return a; //No error
}
}
I hope this intuition answers your question..........
My motors of my NXT2 2.0 is backwards and now everytime I run the command forward() it rolls backwards instead. I am using the DifferentialPilot to move my robot, and therefore want to overwrite several functions in the DifferentialPilot class.
I inherited from that class and overwrote all constructors with my custom ones.
Then I overwrote forward() which should now call backward(), and vice versa.
However, Now I'm getting exceptions, and I can't really tell why.
Here is the overwritten class:
package lejos.robotics.navigation;
import lejos.robotics.RegulatedMotor;
public class CustomDifferentialPilot extends DifferentialPilot {
public CustomDifferentialPilot(final double wheelDiameter, final double trackWidth, final RegulatedMotor leftMotor,
final RegulatedMotor rightMotor) {
super(wheelDiameter, trackWidth, leftMotor, rightMotor);
}
public CustomDifferentialPilot(final double wheelDiameter, final double trackWidth, final RegulatedMotor leftMotor,
final RegulatedMotor rightMotor, final boolean reverse) {
super(wheelDiameter, trackWidth, leftMotor, rightMotor, reverse);
}
public CustomDifferentialPilot(double leftWheelDiameter, double rightWheelDiameter, double trackWidth,
RegulatedMotor leftMotor, RegulatedMotor rightMotor, boolean reverse) {
super(leftWheelDiameter, rightWheelDiameter, trackWidth, leftMotor, rightMotor, reverse);
}
public void forward() {
backward();
}
public void backward() {
forward();
}
}
And my example code for the robot:
import lejos.robotics.navigation.CustomDifferentialPilot;
public class DriveTest {
private static CustomDifferentialPilot diffPilot;
public static void main(String[] args) {
diffPilot = new CustomDifferentialPilot(10, 20, Motor.A, Motor.B);
diffPilot.forward();
}
}
Is calling a function from the superclass, in the subclass within an overwritten method not allowed?
Your main method does not actually create an instance of diffPilot. You should be getting a NullPointerException at diffPilot.forward();.
You should be doing
diffPilot = new CustomDifferentialPilot(...);
in your main method before calling .forward();
Forgot to pass super() to the overridden methods.
public void forward() {
super.backward();
}
public void backward() {
super.forward();
}