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.
Related
I would like have one method declare two Strings and assign them values. Then have another method to read those values.
I have this structure:
public class ABC extends CDE implements EFG {
public void firstMethod(valueOne, valueTwo) {
class TestClass {
public String testValue = valueOne;
public String anotherValue = valueTwo;
}
}
public void readMethod() {
// HERE I WANT TO READ testValue AND ASSIGN IT A NEW VALUE
}
}
How can I do that?
And is there a better way?
Are you sure you need a class?
May be a simple field declaration will be enough:
public class ABC extends CDE implements EFG {
public String testValue;
public String anotherValue;
public void firstMethod(String valueOne, String valueTwo) {
// do whatever you wish with testValue and anotherValue
}
public void readMethod() {
// here you have access to both variables
}
}
Make the local class global and set/read values via instance:
public class ABC extends CDE implements EFG {
class TestClass {
public String testValue = valueOne;
public String anotherValue = valueTwo;
}
private testClassInstance = new TestClass()
public void firstMethod(valueOne, valueTwo) {
testClassInstance.testValue = valueOne
testClassInstance.anotherValue = valueTwo
}
public void readMethod() {
System.out.println(testClassInstance.valueOne)
System.out.println(testClassInstance.valueTwo)
}
}
All you want to do is to create a POJO that holds testValue and anotherValue and declare the class outside of your component class, e.g.:
class ExampleBean {
private String testValue;
private String anotherValue;
//getters and setters
}
Once done, you can hold the reference of that class into your component class and access the value, e.g.:
public class ABC extends CDE implements EFG {
ExampleBean exampleBean = new ExampleBEan();
public void firstMethod(valueOne, valueTwo) {
exampleBean.setValueOne(valueOne);
exampleBean.setAnotherValue(valueTwo);
}
public void readMethod() {
String value = exampleBean.getValueOne();
}
}
Maybe this will fit your criteria?
What you are currently asking for is impossible due to the scope of the inner class.
You could also initialize this private class instance in your constructor.
public class Sample {
class TestClass {
public String testValue;
public String anotherValue;
}
private TestClass localTest = new TestClass();
public void firstMethod(valueOne, valueTwo) {
localTest.testValue = valueOne;
localTest.anotherValue = valueTwo;
}
public void readMethod() {
localTest.testValue = "test1";
localTest.anotherValue = "anotherValue";
System.out.println(localTest.testValue);
}
}
You are declaring a class withing a method , which is not right
You need to understand what a class and a method really mean ( Google Java OOP ) :
1- You should create a class and declare the variables you want
2- make constructors for the default values
3- make setters to set (assign) these values
4- make getters to read those values
I also done this example creating object for both class and call the method is there anyway to override the baseclass?
class Car {
void Max() {
System.out.println("Audi");
}
}
class Speed extends Car {
void Max() {
System.out.println("300");
}
public static void main(String args[]) {
Speed s=new Speed();
s.Max();
}
}
At the risk of being called a "give me the repz" type person...hopefully this helps:
This first class is a BaseClass, you can create a new one by writing:
BaseClass myBaseClass = new BaseClass();
public class BaseClass {
private int aNumber; //This global variable is private and so cannot be overwritten.
int anotherNumber; //This global variable is package scope and so can be accessed by sub-classes in the same package.
protected yetAnotherNumber; //This variable is accessible by any subclasses.
public int numberAvailableToEveryone; //This global variable is accessible to anyone and everyone.
public BaseClass() {} //This is a constructor (no return type)
private void myPrivateMethod() {} //This method cannot be overwritten
void packageScopeMethod() {}
protected void thisMethodCanBeOverwrittenBySubClasses() {}
public void theWorldCanCallMe() {} //extendable to the world, not much different than protected scope tbh
}
Now, to overwrite a method you can create an anonymous class like so:
BaseClass myAnonymousClass = new BaseClass() {
public void theWorldCanCallMe() {
//in here you can override the method to do whatever you want.
}
}
or you could define a subclass like so:
public class SubClass extends BaseClass {
#Override
public void tehWorldCanCallMe() {
//again your new code goes here
}
}
and then instantiate it like so:
SubClass myClassThatOverridesAMethod = new SubClass();
A car example closer to your code:
class Car {
private String name;
int speed = 100;
Car(String name) { //This is the base classes constructor
this.name = name;
}
String max() {
return speed;
}
void run() {
System.out.println(name);
System.out.println(max()); //will print the base speed unless overridden
}
}
class Audi extends Car {
Audi() {
super("Audi")
}
}
class Speed extends Car {
Speed() {
super("Speed");
}
#Override
String max() {
speed = 300;
return speed;
}
public static void main(String args[]) {
Speed s=new Speed();
s.run();
}
}
i'm trying to write anonymous inner class
interface Face{
void seeThis(String what);
}
class Eyes {
public void show(Face f){}
}
public class Seen {
public void test() {
Eyes e = new Eyes();
e.show(new Face() {
#Override
public void seeThis(String what){
System.out.print(what);
}
});
public static void main(String[] args) {
Seen s = new Seen();
s.test();
}
}
How to call seeThis() and how to pass parameter to it?
Method seeThis() belongs to Face class, which instance is anonymous and thus cannot be reached without storing reference to it. If you want to store a reference, you can do this in the following way:
public class Seen {
public Face face;
....
this.face = new Face() { ... };
e.show(this.face);
And then,
Seen s = new Seen();
s.face.seeThis();
Now, regarding passing the parameter. You have two options - declare parameter outside of anonymous class and make it final in order to be reachable by this anonymous class, or replace anonymous class with normal one and pass the parameter to its constructor:
Approach one:
final int parameter = 5;
...(new Face() {
#Override
public void seeThis() {
System.out.println(parameter);
}
});
Approach two:
public class MyFace implements Face() {
private final int parameter;
public MyFace(int parameter) {
this.parameter = parameter;
}
#Override
public void seeThis() {
System.out.println(parameter);
}
}
Then,
...
e.show(new MyFace(10));
Got some incomprehensible exercise in my book.
"Create a class with a non-default constructor (one with arguments) and no default constructor (no "no-arg" constructor). Create a second class that has a method that returns a reference to an object of the first class. Create the object that you return by making an anonymous inner class that inherits from the first class."
Can anyone come out with a source code?
Edit:
I don't understand what the final source code should look like. And I came with this one:
class FirstClass
{
void FirstClass( String str )
{
print( "NonDefaultConstructorClass.constructor(\"" + str + "\")" );
}
}
class SecondClass
{
FirstClass method( String str )
{
return new FirstClass( )
{
{
print( "InnerAnonymousClass.constructor();" );
}
};
}
}
public class task_7
{
public static void main( String[] args )
{
SecondClass scInstance = new SecondClass( );
FirstClass fcinstance = scInstance.method( "Ta ta ta" );
}
}
Honestly, the exercise is quite concise unless you do not know or understand the definition of an inner class. You can find an example of an anonymous inner class here:
http://c2.com/cgi/wiki?AnonymousInnerClass
Otherwise, this concise example illustrates the problem:
/** Class with a non-default constructor and no-default constructor. */
public class A {
private int value;
/** No-arg constructor */
public A() {
this.value = 0;
}
/** Non-default constructor */
public A(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
}
/** Class that has a method that returns a reference to A using an anonymous inner class that inherits from A. */
public class B {
public B() { ; }
/** Returns reference of class A using anonymous inner class inheriting from A */
public A getReference() {
return new A(5) {
public int getValue() {
return super.getValue() * 2;
}
};
}
}
How I can instantiate a object in the List e.g
i like to search for begin in the file , if it finds then add the store the code after it. here is the example
public abstract class Structure
{
private List<Structure> structureList = new ArrayList<Structure>();
protected void setStructure(Filemanager file, String line)
{
/*
* set all values at the object structure
*/
line = file.getSourceLine();
while (!line.contains("END_"))
{
if (line.contains("TRANSLATE"))
{
}
else if (line.contains("BEGIN_OBJECT"))
{
structureList.add(new FunctionalStructure(line));
}
else
{
setValue(line);
}
line = file.getSourceLine();
}
}
protected abstract void setValue(String line);
}
public abstract class FunctionalStructure extends Structure
{
private String name;
public FunctionalStructure(String line)
{
super();
this.name = line.substring(line.indexOf("\"")+1, line.lastIndexOf("\""));
}
public String getName()
{
return this.name;
}
public List<Structure> Startfunctional()
{
return null;
}
protected abstract void setValue(String line);
}
I have problem in in instantiate structureList.add(new FunctionalStructure(line));
Can anyone please tell what is wrong in the above line
I think that FunctionalStructure must be an abstract class (which presumably extends Structure). You cannot instantiate an abstract class.
This is why you get the error like:
Cannot instantiate the type FunctionalStructure
If you created the FunctionalStructure class, perhaps you accidentally marked it as abstract. Assuming it implements the setValue(String) method, you could remove the abstract modifier from the class declaration.
Alternatively, use a suitable concrete class extending FunctionalStructure in the API you are using.
Alternatively, use an anonymous inner class:
structureList.add(new FunctionalStructure(line){
public void setValue(String value) {
// your implementation here
}
});
you might find example below helpful to understand the concept :-
package pack;
public class Demo {
public static void main(String[] args) {
MyGeneric<A> obj = new MyGeneric<A>() ;
//obj.add(new C()) ; //don't compile
obj.testMethod(new A()) ; //fine
obj.testMethod(new B()) ; //fine
}
}
class A{}
class C{}
class B extends A{}
class MyGeneric<T>{
public void testMethod(T t) {
}
}
EDIT : So, there must be a IS-A relation between Structure and FunctionalStructure to successfully compile the code.