- Java Programming for Beginners
- Mark Lassoff
- 311字
- 2021-07-02 15:22:46
Importing class libraries
One thing that's not super human-readable about our program is the long paths to functions such as pow() and println(). Is there a way we could shorten them? There certainly is. If the makers of Java had wanted to, they could have allowed us to call this function by simply typing Math.pow() in all instances. This unfortunately would have some unintended side effects. For example, if there were two libraries linked up to Java and they both declared a Math.pow() function, Java would not know which one to use. Hence, by default, we're expected to link to libraries directly and explicitly.
So, if we'd like to just be able to type out something like Math.pow(), we can import a library into the local space that we're working in. We just need to do an import command above our class and the main() function declaration. All the import command takes as input is the path that we'd like Java to look for when it comes across a keyword, such as pow(), that it doesn't immediately recognize. In order to allow us to employ the easier syntax Math.pow() in our program, we simply need to type import java.lang.Math:
package themathlib; import java.lang.Math; public class TheMathLib { public static void main(String[] args) { double number = 4.321; number = java.lang.Math.pow(number, 4.0); System.out.println(number); } }
There is some special syntax for imports. Let's say we wanted to import all the class libraries in java.lang. To do this, we could replace .Math with .* and make it java.lang.* which translates to "import every library from the java.lang package." I should probably inform you that for those of us working in NetBeans, this import is done by default. However, in this case, we're going to do it explicitly because you may have to do this while working in other Java environments as well.
- JIRA 7 Administration Cookbook(Second Edition)
- 區(qū)塊鏈架構(gòu)與實(shí)現(xiàn):Cosmos詳解
- Mastering Python Networking
- MySQL數(shù)據(jù)庫(kù)基礎(chǔ)實(shí)例教程(微課版)
- RISC-V體系結(jié)構(gòu)編程與實(shí)踐(第2版)
- Python項(xiàng)目實(shí)戰(zhàn)從入門(mén)到精通
- Unity 5.X從入門(mén)到精通
- 數(shù)據(jù)分析與挖掘算法:Python實(shí)戰(zhàn)
- Python預(yù)測(cè)分析與機(jī)器學(xué)習(xí)
- Node.js實(shí)戰(zhàn):分布式系統(tǒng)中的后端服務(wù)開(kāi)發(fā)
- 例說(shuō)FPGA:可直接用于工程項(xiàng)目的第一手經(jīng)驗(yàn)
- Jakarta EE Cookbook
- Java EE程序設(shè)計(jì)與開(kāi)發(fā)實(shí)踐教程
- 前端架構(gòu)設(shè)計(jì)
- 菜鳥(niǎo)成長(zhǎng)之路