Weishi's Engineering Blog

How's Cali treating you?


  • Home

  • Archives

  • Tags

  • Search

constructor for abstract class - java

Posted on 2015-01-21 |
I understand an abstract class as a class that cannot be instantiated.
Then why can it have a constructor?

1. the constructor should be protected. (public is useless since it's not gonna be instantiated. can only be called by subclasses' super())
2. use it to initialize abstract superclass fields.

"In any case, don't forget that if you don't define a constructor, then the compiler will automatically generate one for you (this one is public, has no argument, and does nothing)."
-http://stackoverflow.com/questions/260666



"If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem." -http://docs.oracle.com/javase/tutorial/java/IandI/super.html
Read more »

Polymorphism, variable shadowing/hiding

Posted on 2015-01-21 |
Let's say if superclass and subclass have one instance field named the same - var. Then casting the object will change the result. "((Superclass) subclassObj).var" gives the Superclass's instance field var. So I suppose variable names in Java are resolved by the reference type, not the actual obj type they are referencing. while method names are dynamic binding, which uses the actual obj type. So it comes the polymorphism
Read more »

JAVA - System.currentTimeMillis()

Posted on 2014-09-24 |
Today, when I was trying to generate a series of random number in java code to be an database primary key, I was thinking of
System.currentTimeMillis()

However, it doesn't work as the granularity is actually dependent on the OS. It might be 10 times miliseconds. Anyway, in my for loop it some times give duplicate value.


Also, I find an interesting utility in Eclipse. Let's talk about jpage next time.
Read more »

i = i++

Posted on 2013-12-21 |
The code
int i = 0;
i = i++;
System.out.println(i);
produces the output "0" instead of "1". Why?


Let's take a close look at what the line "i = i++;" does:
  1. "i++" is evaluated. The value of "i++" is the value of i before the increment happens.
  2. As part of the evaluation of "i++", i is incremented by one. Now i has the value of 1;
  3. The assignment is executed. i is assigned the value of "i++", which is the value of i before the increment - that is, 0.


Source: http://www.coderanch.com/how-to/java/PostIncrementOperatorAndAssignment
Read more »
1 2
Weishi Zeng

Weishi Zeng

14 posts
7 tags
GitHub
© 2013 - 2025 Weishi Zeng
Powered by Jekyll
Theme - NexT.Muse