I have got some methods that are common to two subclasses so i have put them in Abstract superclass but there is one method that uses a variable with two different values so i am confused how to implement that method the code is like:
StandardMember class got this method with its own different value for remainingCredit=30 at starting
public void borrowHolding(int holdingId)
throws InsufficientCreditException, MultipleBorrowingException {
// TODO Auto-generated method stub
System.out.println("Hello");
Holding tempHolding = Library.libCollection.getHolding(holdingId);
if (Library.libCollection.getHolding(holdingId) != null) {
if (tempHolding.isOnLoan()) {
System.out.println("Can not be issued Currently on Load");
} else {
System.out.println("Can be issued");
remainingCredit-=tempHolding.getDefaultLoanFee();
System.out.println(getRemainingCredit());
tempHolding.setLoanCheck(true);
currentlyBorrowedHolding.put(holdingId, tempHolding);
System.out.println(remainingCredit);
System.out.println(holdingId);
}
}
PremiumMember Class got same method but the value of remainingCredit is 45, Whereas all the methods common to them are implemented in this AbstractMember class which implements the Member interface. but when i try to call these method from other class i have to initialize the object of AbstractMember in Library Class like this
Member member = new StandardMember();
which is very bad because I can not use the StandardMember object to run the PremiumMember Object's version of same method. so, either i should create new object of PremiumMember Class or i dont know what to do. but if i create two objects then this member object is being used in borrowHolding method which is basically a cascading method in Library Class which in turn calls the borrowHolding method in Member Interface:
public void borrowHolding(int holdingId) throws InsufficientCreditException, MultipleBorrowingException {
if(libCollection.holdingMap==null){
System.out.println("Collection is Empty");
}
if(libCollection.holdingMap.containsKey(holdingId))
member.borrowHolding(holdingId);
}
the problem is i can not create two objects because at runtime i can only call one method. so help me out how to implement this method in Abstract class so that program will detect the difference that which object it should create.
If I understood you correctly, you have a Member abstract class with a field remainingCredit which has to be 30 in one subclass and 45 in another.
Use a protected constructor.
public abstract class Member {
private int remainingCredit;
// Other members
// getters and setters
protected Member(String memId, String memName, int remainingCredit) {
this.memId = memId;
this.memName = memName;
this.remainingCredit = remainingCredit;
}
}
public StandardMember extends Member {
public StandardMember(String memId, String memName) {
super(memId, memName, 30);
}
}
public PremiumMember extends Member {
public PremiumMember(String memId, String memName) {
super(memId, memName, 45);
}
}
Related
i am go through the below method but not getting how my seniors designed.
public LinkedHashMap<String,IPDFField> getFields() {
LinkedHashMap<String, IPDFField> fields = new LinkedHashMap<String, IPDFField>();
//^field1c^lastName^nameSuffix
// Line One
addField(fields,"1_1", new PDFField(27+X_OFF, 718+Y_OFF, new FieldWidthValidation(134F, "^field1_1^firstName^middleName^lastName^nameSuffix")) { //PI tab
#Override
public String getPrintableText(Object o) {
Disposition d = (Disposition) o;
return dataFormattingService.NormalizedPersonName(
d.getFirstName(), d.getMiddleName(), d.getLastName(), d.getNameSuffix()
);
}
});
} //getFileds method ends
from above method they have called below addField Method but what is getPrintableText inside AddField Method
private void addField(HashMap<String, IPDFField> fields, String fieldKey, IPDFField field) {
field.setFieldKey(fieldKey);
if (field.getValidation() != null) {
field.getValidation().setField(field);
}
fields.put(fieldKey, field);
}
above is not full code , the main functionality is we are trying to write content into pdf but i don't want to paste my full code i just need explanation for above logic
addField(/**/, new PDFField(/**/) {
#Override
public String getPrintableText(Object o) {
// ...
}
});
What happens here is the creation of an anonymous inner class.
This anonymous inner class extends the class PDFField and redefines the behavior of the method getPrintableText which is defined in class PDFField.
sorry one more doubt addFiled we have two methods in above , one is anonymous and another is private method,may i know if they are using annonymous class then they could have declared different method name for addField which is private above? – adithyan .p
I'm not sure if I understand that comment...
The anonymous class is
new PDFField(/**/) {
#Override
public String getPrintableText(Object o) {
// ...
}
}
And this is passed as a parameter to the method addField().
There is no restriction on the visibility of the method that gets the anonymous class instance as a parameter.
So I have a concrete class and an abstract class and I am trying to access methods from the concrete class from the abstract one. Store currently contains many getters that the member class needs. Currently get null pointer exception.
public abstract class members{
// Trying to refrence the store object
Store store;
public void someMethod(){
// I want to be able to access all the methods from the store class
// eg
store.showVideoCollection();
}
}
public class store {
// This class has already been instantiated, just one object for it.
public void showVideoCollection(){
// Stuff here
}
public void otherMethod(){
// Stuff here
}
}
EDIT:
In the main method
public class start {
public start() {
store = new Store(); // Don't want to create more than 1 store object.
}
Thanks
In order to store a Store instance you must instantiate it. As is, you declare the variable store but you never initialize it (so it's null). I think you wanted something like
// Trying to refrence the store object
Store store = new Store(); // <-- create a Store and assign it to store.
Alternatively, you could make Store a Singleton. The linked Wikipedia page says (in part) the singleton pattern is a design pattern that restricts the instantiation of a class to one object.
public final class Store {
public static Store getInstance() {
return _instance;
}
private static final Store _instance = new Store();
private Store() {
}
public void showVideoCollection(){
// Stuff here
}
public void otherMethod(){
// Stuff here
}
}
i have my DTO class that is :
public class EmailResponse {
// Make public to avoid getters and setters
public Email email;
public RequestData reqData;
public EmailResponse() {
super();
}
}
and i want to implement to it this interface:
public interface IAssertionErrorDo {
public void onErrorDo();
}
but i want to do it during execution, i don't want to touch "EmailResponse" because it would not be ok to make it implements that interface due they don't belong to the same layer, i mean, EmailResponse would belong to service layer and IAssertionError would belong to test layer. I am using TestNG.
Do you know how i could do this? Regards
EDIT:
My implementation is this:
EmailResponse emailResponse = emailService.getUserEmail(userId);
And the reason i want to do this "injection" is because i have
public class LoggingAssert
extends Assertion {
private static final Logger LOGGER = LoggerFactory.getLogger(LoggingAssert.class);
private IAssertionErrorDo dataE;
#Override
public void onAssertFailure(IAssert a, AssertionError ex) {
LOGGER.info("[ERROR] " + a.getMessage());
if (this.dataE != null) {
this.dataE.onErrorDo();
}
}
public LoggingAssert setOnErrorDo(IAssertionErrorDo object) {
this.object = object;
return this;
}
}
loggingAssert.setOnErrorDo(emailResponse).assertNotNull(emailResponse.getEmail().getId(),
"Checking created email doesn't exists");
So i want to if assert fails execute method onErrorDo() from emailResponse
You could do
public class MyEmailResponse extends EmailResponse implements IAssertionErrorDo {
...
}
implementation calls in interfaces, you can call more than 1 interface if you want by adding commas to separate them..
to call interface methods you simply just use the method's name.
like this:
public class MyEmailResponse implements IAssertionErrorDo
{
public void onErrorDo() {//define it's behavior}
}
if you extend a class you use:
super.MyMethod()
to call the a method inside the extended class, but if you already have an extended class and want a method from another class you have to create an object for that class first then call it, thus:
MyClass mc = new MyClass();
if it is in a different package then
myPackage.MyClass mc = new myPackage.MyClass();
then you call your method from that class using the object you created, which is in this case mc.. so:
mc.MyMethod();
if you want it to return a variable then you will need to add a return statement in that method with the variable you want it to return.
interfaces are usually used for global an changing environments (dynamics), for example if you developed a program and it needs a driver to connect to databases then you will make an interface and send it to the database developers, and each one will fill the codes in that interface and send it back... this guarantees consistency.
when you implement an interface you have to define every method inside it (even if you leave it empty) and you cannot change the interface's methods names nor add... it is used in other areas as well, i don't think you need to use it in your case.
I know why my problem is occurring but i'm unsure on how to deal with it.
So I have 3 classes, 1 of these holds my getters & setters. In one class I am setting the values, in the other I am getting the values. When I get the values they are returned null. This is obviously because the two instances of the getter/setter object I created in the classes are separate from one another. What i'm trying to find out is how I can set the values in one class and get them in another without having two separate instances of the getter/setter class. My wording is terrible so here's a more visual explanation:
Class 1
Encapsulation encap = new Encapsulation();
encap.setValue(10);
Class 2
Encapsulation encap = new Encapsulation();
encap.getValue(); //I want this to return 10
Class 3 (Encapsulation)
private int value;
public void setValue(int value){
this.value = value;
}
public int getValue(){
return value
}
In Class2, you are creating a new instance of class Encapsulation. (Notice new Encapsulation()). So obviously, that won't hold the values.
Instead, I would suggest you two solutions:
First:
Save that object in an Application class as you are working on Android application.
public class TestApplication extends Application {
public Encapsulation tempClass;
public TestApplication () {
// TODO Auto-generated constructor stub
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
}
public Encapsulation getTempClass() {
return tempClass;
}
public void setTempClass(Encapsulation tempClass) {
this.tempClass = tempClass;
}
}
Now in your Activity:
//after setContentView
testAppObj = (TestApplication) getApplication();
testAppObj.setTempClass(myTempClassObj);
//retrieve as:
Encapsulation obj = testAppObj.getTempClass();
You must register your Application class in your manifest file just like you register your activities:
<application
android:name="com.pkg.test.TestApplication " />
Second:
Keep object encap as static in Class1. So you can access it from calss2. (I don't prefer static.)
Hope it helps.
Make value static, it will keep the same value across all Encapsulation instances
private static int value;
public void setValue(int aValue){
value = aValue;
}
public int getValue(){
return value;
}
Just declare an object of the Encapsulation class once,and use the same instance to call the getter and setter.
Like this:
Encapsulation encap = new Encapsulation();
encap.setValue(10);
encap.getValue();
It works.
I want to create an object that is linked in some way to another object of the same class. This link should be specified in the constructor of the new object.
public class Counter {
public Counter(){
// default counter constructor
}
public Counter(Counter oldCounter){
// do stuff specifying new object is linked to oldCounter
}
public void someMethod(){
// this method should call a method belonging to oldCounter
oldCounter.someOtherMethod();
}
Tried searching the archives for an answer, but couldn't find anything...
Remember the argument as a private instance member, then use that member:
public class Counter {
// The instance member we'll use, note that we initialize it to `null`
// because you have a zero-args constructor, so we want to be sure we
// know whether we have one or not
private Counter otherCounter = null;
public Counter() {}
public Counter(Counter oldCounter) {
// Remember it here
this.otherCounter = oldCounter;
}
public void someMethod() {
// Use it here
if (this.otherCounter != null) {
this.otherCOunter.someOtherMethod();
}
}
}
To achieve what you want Crowder's answer is good enough.
You are having two version of same class. For me it seems that you need to follow some design pattern to better organize your code. In this case Factory Pattern may be a good choice.