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

  • The Java Workshop
  • David Cuartielles Andreas G?ransson Eric Foster Johnson
  • 437字
  • 2021-06-11 13:05:22

Inheritance in Java

Inheritance is a key principle of object-oriented programming. It entails the transfer of the existing structure of one class, including its constructor, variables, and methods, to a different class. The new class is called the child class (or subclass), while the one it's inheriting from is called the parent class (or superclass). We say that the child class extends the parent one. The child class is said to extend the parent class in the sense that it not only inherits whatever structures are defined by the parent, but it also creates new structures. The following example shows a parent class and how the child class extends it by adding a new method to it. We will take the Computer class we defined earlier as a parent and create a new class called Tablet, which is a type of computer.

Example05.java

20 class Tablet extends Computer {

21     // variables

22     private double screenSize;  // in inches

23 

24     // methods

25     void setScreenSize ( double _screenSize ) {

26         screenSize = _screenSize;

27     }

28 

29     double getScreenSize () {

30         return screenSize;

31     }

32 }

33 

34 public class Example05 {

35     public static void main(String[] args) {

36         Tablet myTab = new Tablet();

37         myTab.setCpuSpeed( 2.5 );

38         myTab.setScreenSize( 10 );

39         System.out.println( myTab.getCpuSpeed() );

40         System.out.println( myTab.getScreenSize() );

41     }

42 }

Notice how the definition of the Tablet class does not include any methods called setCpuSpeed() or getCpuSpeed(); however, when calling them, not only does the program not give any errors, but the commands are also successfully launched.

This is because the definition of the Tablet class extends the Computer class, thus inheriting all its internal objects, variables, and methods. When creating an object of the Tablet class, such as myTab, the JVM reserves space in memory for a cpuSpeed variable and the setter and getter methods that go with it.

主站蜘蛛池模板: 丁青县| 贡觉县| 临朐县| 莎车县| 高要市| 桂阳县| 广安市| 大石桥市| 迭部县| 隆回县| 吐鲁番市| 汶川县| 嘉义县| 阳谷县| 芮城县| 衡阳县| 昔阳县| 日照市| 泸定县| 台中市| 勃利县| 沭阳县| 磐石市| 抚顺市| 南开区| 五台县| 鹤山市| 青龙| 台北市| 鹿泉市| 德令哈市| 牙克石市| 阿拉善盟| 岳普湖县| 江永县| 闽侯县| 余姚市| 正镶白旗| 唐海县| 台北县| 沁阳市|