Copy constructor of subclass that has its own variables [duplicate] - java

This question already has answers here:
how to copy SubClass object in BaseClass copy constructor
(3 answers)
Java: How to copy an object so it will be from the same subclass?
(4 answers)
Closed 4 years ago.
I have a subclass called CDAccount that has its own variables that aren't defined in the super class.
private Calendar maturityDate;
private int termOfCD;
The subclass also has a copy constructor that takes in a superclass object.
public CDAccount(Account cd){
super(cd);
}
This constructor is called by this line of code that's in a different class.
if (accounts.get(index).getType().equals("CD")) {
return new CDAccount(accounts.get(index));
}
I'm looking for a way to set the subclass variables in the copy constructor. I thought I would be able to do it with the object it takes in, because I created the object as a subclass object before setting it into the array of superclass objects.

Casting should do the trick for you:
public CDAccount(Account cd) {
super(cd);
if(cd instanceof CDAccount) {
this.maturityDate = ((CDAccount)cd).maturityDate;
this.termOfCD=((CDAccount)cd).termOfCD;
}
else {
this.maturityDate = null;
this.termOfCD= null;
}
}
This works because of the way encapsulation is implemented in Java: private variables are accessible to other instances of the same class.

The best practice would be overloading the constructor like this.
public CDAccount(CDAccount cd){
super(cd);
this.maturityDate = cd.getMaturityDate()
this.termOfCD = cd.getTermOfCD()
}
public CDAccount(Account cd){
super(cd);
}
This works for me on Java JDK v10.1

Related

When to use static/non-static variable in JAVA [duplicate]

This question already has answers here:
When to use static methods
(24 answers)
When to use static variables/methods and when to use instance variables/methods in Java? [closed]
(5 answers)
Java Static vs Instance
(9 answers)
How and where to use Static modifier in Java?
(7 answers)
Closed 2 years ago.
I don't know when to use a static/non-static variable in a program.
package slides;
public class Person {
String name;
int age;
boolean isStaff;
public Person(String name, int age, boolean isStaff) {
// TODO Auto-generated constructor stub
this.name = name;
this.age = age;
this.isStaff = isStaff;
System.out.println(this);
}
/*
public static boolean Staf () {
return isStaff;
}
*/
}
I understand the difference between the non-static/static variable but I just don't know when to use each. So in the above code, why the function Staf can not be static? (and when it should be static?)
According to the last question, you do not understand the difference. Every non-static method implicitly receives this (as an argument). Static methods are not bound to some instances, so you just can not reference non-static fields. Static stuff can reference only static stuff.
static could be used:
For Singleton pattern, for example;
Or if you want to utilize class as simple namespace;
Or just do not like OOP and going to use COP)
The static method Staf() is not allowed to return class instance variables because Staf() can be invoked without the class Person instance being created. Therefore, Staf() can only return static variables.
You can not access non-static (instance) variables unless you do so with a) a reference to an instance (myPerson.isStaff, which would violate encapsulation) or b) from within a non-static (instance) method.
As to when you should use static, there are many discussions and diatribes on this very website which can easily be found.

How to pass a value in a constructor from one class and set the value in its default constructor [duplicate]

This question already has answers here:
Constructor overloading in Java - best practice
(5 answers)
Closed 5 years ago.
I have a situation where i have to pass a value to a constructor from a class and i also have to call the constructor from another class but while calling the constructor from the second class i can not pass the value to its constructor.How i can achieve this ? I am trying to define the value in its default constructor , but while i am calling the constructor i need to pass the value which i want to avoid. This is my current scenario
// I have to pass the value here
DNQLtrDataAccessor data = new DNQLtrDataAccessor(aValue);
This is the corresponding class:
public class DNQLtrDataAccessor {
private static final Logger LOGGER = Logger.getLogger(DNQLtrDataAccessor.class);
String val;
public DNQLtrDataAccessor(String val) {
this.val = val;
}
And here is the other class where I don't want to provide a value:
public class UWCompanyInfo {
public void loadData(Document document, Connection connection) throws Exception {
//Here i can not pass the value
DNQLtrDataAccessor dataAccessor = new DNQLtrDataAccessor();
If you define an overloaded constructor, you need to define default constructor explicitly.

Java Constructor call [duplicate]

This question already has answers here:
What are all the different ways to create an object in Java?
(22 answers)
How many ways to create object in java? [closed]
(1 answer)
Closed 5 years ago.
Is there any other way to call constructor, other than new object creation from new operator?
I think when constructor chaining happens in inheritance then also constructor gets called but it does not create parent class object.
Yes and no, one way is to have your contructor call some method:
public class SomeClass {
public SomeClass() {
init();
}
public final void init() {
// do something
}
}
Then call init() again later when needed

Assigning an argument of a class(a) to another class's(b) variable by calling class(b) constructor [duplicate]

This question already has answers here:
Calling superclass from a subclass constructor in Java
(4 answers)
Closed 7 years ago.
What I need to do: //Constructor that initializes b to inVal1 and the inherited a
// to inVal2 by using the BaseExample constructor.
public DerivedExample(int inVal1, int inVal2);
How do you call the class BaseExample's variable, in class DerivedExample by using BaseExample constructor in DerivedExample constructor? I have checked numerous articles in stackoverflow and it hasn't helped figure this out. Any help will be greatly appreciated. This is my code:
BaseExample Class (and no I am not allowed to make the variable protected on this example):
public class BaseExample {
private int a;
public BaseExample(int inVal) {
a = inVal;
}
public BaseExample(BaseExample other){
a = other.a;
}
public String toString(){
return String.valueOf(a);
}
}
DerivedExample Class (Updated):
public class DerivedExample extends BaseExample {
private int b;
public DerivedExample(int inVal1, int inVal2){
super(inVal2);
a = inVal2;
}
}
The super method worked. Now how would I call it if I am asked this:
Returns a reference to a string containing the value stored in
the inherited varible a followed by a colon followed by the
value stored in b
public String toString()
I have tried this:
public String toString(){
int base = new BaseExample(b);
return String.valueOf(base:this.b);
}
If I put two returns, it would give me an error of unreachable code. And if I put a super inside the valueOf it doesn't work. And this doesn't work as well. How is this executed?
If I understand correctly, this might be of use to you. Super can be used to call the base class's constructor to instantiate its variables for you.

Method Class in Reflection API [duplicate]

This question already has answers here:
How do I access private methods and private data members via reflection?
(6 answers)
What does it mean for a method to be public/private/other in java? [closed]
(6 answers)
Closed 8 years ago.
This program ran fine when test() method was public but as soon as I changed its modifier to private it showed Run time error.Can anybody explain why?
package ObjectClass;
import java.lang.reflect.Method;
public class reflect8 {
public static void main(String[] args) throws Exception {
Class c1 = Class.forName("ObjectClass.Reflect8A");
Object obj = c1.newInstance();
Method m1 = c1.getDeclaredMethod("test");
m1.invoke(obj);
}
}
class Reflect8A {
private void test() {
System.out.println("from test...");
}
}
Here is why you need to call setAccessible(true) even if getDeclaredMethod returns the private method.
Javadoc of getDeclaredMethod (emphasis mine):
Returns an array containing Method objects reflecting all the declared methods of the class or interface represented by this Class object, including public, protected, default (package) access, and private methods, but excluding inherited methods.
Javadoc of invoke:
Throws IllegalAccessException - if this Method object is enforcing Java language access control and the underlying method is inaccessible.
Javadoc of setAccessible (emphasis mine):
Set the accessible flag for this object to the indicated boolean value. A value of true indicates that the reflected object should suppress Java language access checking when it is used.
Method m1 = c1.getDeclaredMethod("test");
m1.setAccessible(true);
m1.invoke(obj);

Categories