List<Structure> in java - java

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.

Related

How to access a parent class variable via a child class

I am trying to re-build an OOP approach to mobile verification at the developers discretion. The concept I come up with is to allow for interfaces to manipulate the class. If the class implements the interface, then the verify method will be executed.
The problem I am facing, because I am only used to programming in less strongly-typed languages (PHP) is how to get a protected variable from a class extending the current class.
_areaCodes.stream().forEach(o -> {
try {
int prefix = Integer.parseInt(this._mobileNumber.charAt(0), this._mobileNumber.charAt(1));
} catch (Exception e) {}
});
This line of code is now giving me an error
_mobileNumber cannot be resolved or is not a field
Here is my full code and here is an example I wrote of the same concept in PHP which I am trying to implement in Java.
import java.util.ArrayList;
interface Verification
{
public void initVerification();
}
class AreaCode
{
private int _code;
private String _country;
public AreaCode(int code, String country)
{
this._code = code;
this._country = country;
}
public int getAreaCode() { return this._code; }
public String getAreaCountry() { return this._country; }
}
class VerificationHandler
{
private ArrayList<AreaCode> _areaCodes = new ArrayList<AreaCode>() {{
this.add(new AreaCode(44, "UNITED KINGDOM"));
this.add(new AreaCode(91, "INDIA"));
}};
public void initVerification()
{
if(this instanceof Verification) {
this.verify();
}
}
protected void verify()
{
_areaCodes.stream().forEach(o -> {
try {
int prefix = Integer.parseInt(this._mobileNumber.charAt(0), this._mobileNumber.charAt(1));
} catch (Exception e) {}
});
}
}
class Main extends VerificationHandler implements Verification {
protected String _mobileNumber = "+447435217761";
}
public class Hack1337 { public static void main(String[] args) { new Main(); } }
How can I retrieve a variable in a class extending another, ie:
class A { public String getB() { return this.b; } }
class B extends A { protected String b = 'A should get this'; }
B b = new B().getB();
Only instances of class B, or sub-classes of B can access the b instance variable directly (unless you cast A to B within the body of the A class, which is bad practice).
You can give class A read-only access to that value by overriding getB():
class B extends A
{
protected String b = 'A should get this';
#Override
public String getB() {
return this.b;
}
}
and you may also want to make the getB() method abstract in class A (which means making class A abstract):
abstract class A
{
public abstract String getB();
}
This would only make sense if different sub-classes of A are expected to return different things in getB(). Otherwise, you may as well move the b variable to the base class A.

Implement a common function accepting argument of two different classes?

I have two classes A and B and they both have a common field in them, and I want to create a function in which if I pass Class A object then I want to set that common field value to the passed value and if I pass Class B object then I want to set that common field value to the passed value. Can anyone please tell me how can I do this, I am new to Java Generic Classes.
Otherwise I would have to make two different functions OR I would have to make an if and else which would decide that passed object belongs to which class ??
Class A
public class A{
int footer;
public void setFooter(int fo) {
footer = fo;
}
}
Class B
public class B{
int footer;
public void setFooter(int fo) {
footer = fo;
}
}
Class D
public class D{
public void change_footer(T generic_param, int value) {
generic_param.setFooter(value);
}
}
Class HelloWorld
public class HelloWorld{
public static void main(String []args){
Here I want to call
A a = new A();
new D().change_footer(a, 5);
B b = new B();
new D().change_footer(b, 5)
}
}
Thank You
And if I got all of the question wrong, and nor A nor B are generic, AND the type of field is fixed.
then you mean something like:
class D {
/*public <T extends Super> would be muuuch nicer here as well!*/
public /*static*/ <T> void change_footer(T obj, int data) {
//otherwise, you could just cast to Super...and set dat field.
if (obj instanceof A) {
((A) obj).setField(data);
} else if (obj instanceof B) {
((B) obj).setField(data);
} // else ... ?
}
}
Original answer:
Easy peasy (the "straight forward" implementation produces the desired results.):
class A<T> {
T daField;
public void setField(T pField) {
daField = pField;
}
public T getField() {
return daField;
}
}
class B<T> extends A {//empty
}
class Test {
public static void main(String... args) {
B<Object> testB1 = new B<>(); //
testB1.setField(new Object());
System.out.println(testB1.getField());
B<String> testB2 = new B<>();
testB2.setField("blah blah");
System.out.println(testB2.getField());
B<Integer> testB3 = new B<>();
testB3.setField(42);
System.out.println(testB3.getField());
}
}
System.out:
java.lang.Object#6d06d69c
blah blah
42
It get's (little) more complicated, when you want to instantiate Ts ...but still possible/other question. :)
Edit to your comment:
If there's only one common field, then why not:
/*abstract */class Super<T> {
T daField;
public void setField(T pField) {
daField = pField;
}
public T getField() {
return daField;
}
}
? ...and:
class A<T> extends Super { ... }
class B<T> extends Super { ... }

How to read and write to variables of an abstract class

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.

Anonymous inner classes in Java

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

Extends JAVA class which is in other class

IDsmCore.java (interface class)
public interface IDsmCore
{
public void Initialize( String path, String fileName );
public void Uninitialize( );
}
IDsmToken.java (interface class)
public interface IDsmToken
{
public String GetID( );
public void SetID( String id );
}
DsmCore.java (interface implementation)
public class DsmCore implements IDsmCore
{
#Override
public void Initialize( String path, String fileName ) {
// Some code goes here.
}
#Override
public void Uninitialize( ) {
// Some code goes here.
}
public class DsmToken implements IDsmToken
{
#Override
public String GetID( ) {
// Some code goes here.
}
#Override
public void SetID( String id ) {
// Some code goes here.
}
}
}
How you can see DsmToken class is in the DsmCore class. Now I want to extends DsmToken class, for example I can extends DsmCore in this way:
public class MyExtendedDsmCore extends DsmCore
{
}
And how I can extends DsmToken ?
If the inner class is not qualified as static you're out of luck.
public class MyExtendedDsmCore extends DsmCore.DsmToken {
}
and DsmToken should be static.
Make it static class. But, if you are going to extend the class in two different classes I'd suggest to put it in its own file.
public class MyExtendedDsmCore extends DsmCore impliments IDsmCore since it is an interface.

Categories

Resources