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
Related
This question already has answers here:
Why am I able to call private method?
(8 answers)
Closed 3 years ago.
I am studying for the OCA Exam and came across this code:
public class Driver {
private void printColor(String color) {
color = "purple";
System.out.print(color);
}
public static void main(String[] args) {
new Driver().printColor("blue");
}
}
The question asks "What is the outcome of this piece of code". I initially thought it will be "it does not compile" because you have an object instance trying to access a private method. But, it turns out to be "purple".
Why is it "purple" and not "it does not compile"? I know the Driver instances lives in the same class it is declared in, but why it still have the privilege to access private methods?
Thank you
private means that the method is inaccessible outside the class.
Since your main method is inside the Driver class, then the private methods of Driver are accessible.
I think you missunderstood what private means. It simply means: "You can't access this method from outside the Driver-class." And since you are inside the class, the compiler allows the access.
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
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.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have defined two constructors in my code
public SAPRoleImpl()
{
dateParser=new SimpleDateFormat(MIDDAY_DATE_FORMAT);
dateParser.setTimeZone(TimeZone.getTimeZone("GMT"));
Calendar c=Calendar.getInstance(TimeZone.getTimeZone("GMT"));
c.set(Calendar.HOUR_OF_DAY,12);
c.set(Calendar.MINUTE,0);
c.set(Calendar.SECOND,0);
c.set(Calendar.MILLISECOND,0);
setStartDate(c.getTime());
}
public SAPRoleImpl(String formattedRole)
{
this();
...
}
When I execute the below code:
public static void main(String[] args) {
SAPRoleImpl sapRole = new SAPRoleImpl("abc|abcdesc||");
System.out.println(sapRole);
}
It gives this output
:abc|20170127||
This is as expected. But when I want an output of only
abc|||
i.e no start date is to be initialized, I tried this code:
public SAPRoleImpl()
{
}
public SAPRoleImpl(String formattedRole)
{
this();
...
}
This led to a NullPointerException. Probably, It seems that the startdate is null but I am not able to understand the reason behind the same.
Can any one please help me to understand?
Obviously, you have a field startDate that only gets assigned a value when you call the method setStartDate().
When you omit calling that method within your constructor, then that field stays with null.
And most likely, you are then calling some method like toString() on that null field.
Btw: you get your constructor chaining wrong.
The normal way is that you you call a ctor that takes more arguments, like:
public public SAPRoleImpl() {
this(SOME_DEFAULT_FORMAT_STRING);
}
public SAPRoleImpl(String format) {
dateParser=new SimpleDateFormat(format);
...
setStartDate(c.getTime());
}
In other words: you absolutely want to put your "real" init code into exactly one constructor; or maybe one init method if there is no other way but doing slightly different things within multiple constructors.
This question already has answers here:
Nested functions in Java
(8 answers)
Closed 6 years ago.
Is it possible to define a function within a function in Java? I am trying to do something like:
public static boolean fun1()
{
static void fun2()
{
body of function.
}
fun();
return returnValue;
}
but I am getting error Illegal start of expression.
The reason you cannot do this is that functions must be methods attached to a class. Unlike JavaScript and similar languages, functions are not a data type. There is a movement to make them into one to support closures in Java (hopefully in Java 8), but as of Java 6 and 7, it's not supported. If you wanted to do something similar, you could do this:
interface MyFun {
void fun2();
}
public static boolean fun1()
{
MyFun fun2 = new MyFun() {
public void fun2() {
//....
}
};
fun2.fun2();
return returnValue;
}
You cannot (and in Java they are called methods).
You can, however, define an anonymous class inside of a method, and call its methods.