官术网_书友最值得收藏!

The structure of Java code – revisited

We have already seen that each time we create a new Android project we also create a new Java package, as a kind of container for the code we will write.

We have also learned about and played around with classes. We have imported and taken direct advantage of classes from the Android API such as Log and Toast. We have also used the AppCompatActivity class, but in a different manner to that of Log and Toast. You might remember the first line of code in all our projects so far, after the import statements, used the extends keyword:

public class MyActivity extends AppCompatActivity {

When we extend a class as opposed to just importing it, we are kind of making it our own. In fact, if you take another look at the line of code you can see that we are making a new class, with a new name, MyActivity, but basing it on the AppCompatActivity class from the Android API.

Note

AppCompatActivity is a slightly modified version of Activity. It basically provides extra features for older versions of Android that would otherwise not be present. Everything we have discussed about Activity is equally true for AppCompatActivity. We will see some more variations on the Activity class as we progress. It is entirely possible that you have a different class in place of AppCompatActivity, dependent upon changes that have taken place since this was written. Updates of Android Studio will often change the default Activity class that it uses when it creates a new project. As long as the name ends in …Activity it doesn't matter because everything we have discussed and will discuss is equally true. I will usually just refer to this class simply as Activity.

In summary, we can import classes to use them, we can extend classes to use them and, very importantly, we will eventually make our own classes.

Tip

The important point

Classes, in their various forms, are the foundation of every single line of code in Java. Everything in Java is, or is part of, a class.

Our own classes and those written by others are the building blocks of our code, and the methods within the classes wrap the functional code, the code that actually does the work.

We can write methods within the classes that we extend, as we did with topClick and bottomClick in Chapter 2, Java – First Contact. Furthermore, we overrode methods that are already part of classes written by others, such as onCreate, onPause, and so on.

However, the only code that we put in these methods was a few calls using Toast and Log. We aren't going to code the next killer app with just that.

主站蜘蛛池模板: 锡林浩特市| 手机| 西乌珠穆沁旗| 山东省| 武汉市| 津市市| 红原县| 漠河县| 贡觉县| 夹江县| 天津市| 营口市| 大连市| 隆尧县| 延津县| 安庆市| 修水县| 拉萨市| 德阳市| 衡阳市| 横峰县| 新密市| 铁岭县| 昆明市| 曲阳县| 奉化市| 凤翔县| 桦甸市| 错那县| 通化县| 永登县| 临高县| 金昌市| 宜春市| 舒兰市| 五大连池市| 集贤县| 灵石县| 濮阳市| 龙游县| 府谷县|