amk是什么品牌| 肩膀疼是什么原因| 喝什么茶降血脂| 德国高速为什么不限速| 青枝骨折是什么意思| 一月十八号是什么星座| 人造海蜇丝是什么做的| 我宣你 是什么意思| 田七煲汤配什么材料| 人黄是什么| 什么时候有胎心胎芽| 什么叫同房| 黄油可以做什么美食| 低聚糖是什么| 吃二甲双胍为什么会瘦| 不拘一格是什么意思| 经常胃胀气是什么原因引起的| 莫名其妙的心情不好是什么原因| 月忌日是什么意思| 什么事情只能用一只手去做| 冰心原名什么| 什么叫物理| 格桑花的花语是什么| 婴儿游泳有什么好处和坏处| 糟卤对身体有什么危害| 明年是什么生肖| 甲减挂什么科| 左金丸治什么病最好| 意犹未尽什么意思| 小孩抽动症是什么引起的| 牙龈肿痛吃什么药最好| 茯茶是什么茶| 头晕呕吐挂什么科| 肩膀疼吃什么药| 肾虚腰疼吃什么药最有效| 油性皮肤适合用什么护肤品| 孽缘是什么意思| 肚脐左边是什么器官| 胃火吃什么中成药| 甲状腺结节忌口什么| 碧玺五行属什么| 儿童湿疹用什么药膏| b是什么元素| 类胡萝卜素主要吸收什么光| 立事牙疼吃什么药| 为什么会长痔疮| 游手好闲是什么意思| 尿微量白蛋白高吃什么药| 为什么要文化大革命| 梦到自己流鼻血是什么预兆| 米干是什么| 传宗接代是什么意思| 小孩肠胃感冒吃什么药比较好| 下午1点到3点是什么时辰| 宝宝发烧挂什么科| 养兰花用什么土最好| 胸椎退行性变什么意思| 三人死亡属于什么事故| 人体第一道防线是什么| 戍怎么读音是什么| 拜阿司匹林和阿司匹林有什么区别| 月经量少是什么原因| 神经痛吃什么药效果好| 腹主动脉钙化是什么意思| h 是什么意思| 来大姨妈能吃什么水果| 白舌苔很厚是什么病症| tony是什么意思| 苯中毒是什么症状| 血压测不出来什么原因| 肠胃炎能吃什么| 睡觉头晕是什么原因引起的| 做梦梦见考试是什么意思| 尿酸高吃什么药降尿酸效果好| 戈美其鞋子是什么档次| 孔雀喜欢吃什么食物| 掉头发是什么原因女性| 视力模糊用什么眼药水| 莳花弄草是什么意思| 县公安局长什么级别| 社会科学院是干什么的| 什么动物最怕水| 耳膜穿孔是什么症状| 早上起床腰酸痛是什么原因| 达人是什么意思| 猪八戒是什么生肖| 锁水是什么意思| 吉加页读什么| 胃疼能吃什么水果| 卫生纸是什么垃圾| 拉肚子吃什么药好使| 属猴的是什么星座| 银行卡销户是什么意思| at什么意思| 十斋日是什么意思| 九月十号是什么节日| 三杯鸡为什么叫三杯鸡| 做梦笑出声是什么预兆| 口是心非是什么动物| 火花塞坏了有什么症状| 小酌怡情下一句是什么| 罗红霉素治什么病| 老年人便秘吃什么好| 偏光镜什么意思| 棒棒糖是什么意思| 腿肿是什么原因引起的| 痛风可以喝什么饮料| 女人眉毛稀少代表什么| 蜈蚣吃什么| 眼睛突然红了是什么原因| 钟点房是什么意思| siri什么意思| 臆想是什么意思| 生孩子前要注意什么| 四不像长什么样| josiny是什么牌子| 云南白药植物长什么样| 豆角炒什么| 腋毛有什么作用| 鸡咳嗽吃什么药| 天花是什么病| 指什么为什么| 晚上睡觉腿抽筋是什么原因| 潜规则是什么意思| 五月二十一号是什么星座| 盲约大结局是什么| 景泰蓝是什么地方的特种工艺| 菊花的功效是什么| 钙对人体有什么作用| remember是什么意思| 头发软化和拉直有什么区别| 属狗适合佩戴什么饰品| 淡水鱼什么鱼最好吃| 深耕是什么意思| belle什么意思| 生日送百合花代表什么| 什么的花蕾| 坐怀不乱柳下惠什么意思| 一直不射精是什么原因| 蜂蜜有什么功效和作用| 秦始皇长什么样| 石家庄有什么好玩的景点| marni是什么牌子| 沼泽地是什么意思| 脐带血能治疗什么病| 畏寒怕冷是什么原因| 甲状腺低回声什么意思| 不务正业是什么意思| 腰椎间盘突出是什么原因引起的| 阿普唑仑是什么药| 铂金是什么颜色| 刻舟求剑什么意思| 什么叫脑梗| 为什么会出现彩虹| 老年人腿浮肿是什么原因引起的| 十一月份属于什么星座| 艾滋通过什么途径传播| 龟头感染用什么药| 畅字五行属什么| 儿童肚子痛吃什么药| 下午6点半是什么时辰| 质问是什么意思啊| 热伤风感冒吃什么药好| 白细胞偏高是什么原因引起的| 808是什么意思| 双花是什么中药| 男人脚肿是什么原因| 事急从权是什么意思| 生化常规主要是检查什么的| 早上起床想吐是什么原因| 孕妇吃什么| lirs 是什么意思| 乙醇和酒精有什么区别| 什么是强迫症有哪些表现| b7是什么意思| 市组织部长是什么级别| 梦见狗打架是什么意思| lane是什么意思| 聚宝盆是什么意思| 晚上3点是什么时辰| 腊肉炒什么菜好吃| 生物膜是什么| 为什么手脚老是出汗| 3月26号是什么星座| 生理性是什么意思| 什么颜色代表水| 南宁有什么好玩的地方| 乳糖不耐受吃什么药| 05是什么生肖| 太是什么意思| ih是什么意思| 黄芪什么人不能吃| 什么食物属于发物| 高潮是什么感觉| 头皮屑多是什么原因怎么去除| 澳门是什么花| 3月3是什么星座| 二级医院什么意思| 骨皮质断裂是什么意思| 澳门回归是什么时候| 包皮手术挂什么科| 拔完牙吃什么消炎药| 嬴荡和嬴政什么关系| 4月14日是什么星座| 芒果和什么榨汁好喝| 相伴是什么意思| 莆田系是什么意思啊| 女人脚肿是什么原因| 为什么腋下会长小肉揪| 鸡涌是什么意思| 肚子胀气吃什么药| 什么人不能喝大麦茶| 周吴郑王是什么意思| 手被辣椒辣了用什么方法解辣| 儿童口腔溃疡用什么药| 善根是什么意思| 睾酮素低了有什么症状| 冰心原名叫什么| 13数字代表什么意思| 细水长流是什么意思| 胃糜烂吃什么药可以根治| 褶子是什么意思| 真心是什么意思| 吃中药忌口都忌什么| 到此为止是什么意思| 睾丸痛吃什么消炎药| 布洛芬过量有什么危害| 夏天适合吃什么菜| 吕洞宾是什么生肖| 薄荷不能和什么一起吃| 什么是微信号| 拉肚子适合吃什么食物| 芥菜长什么样子图片| 吃什么药不能献血| 优生优育检查什么项目| 梦到装修房子是什么征兆| 国家电网是什么编制| 做梦梦到牙齿掉了是什么意思| 三七治什么病最好| 晚上睡觉容易醒是什么原因| 月经推后是什么原因| 1931年属什么生肖| c1能开什么车| 为什么感冒喝白酒好了| 胸闷是什么原因引起的| 道家思想的核心是什么| 中医调理身体挂什么科| 什么是犯罪| 红眼病有什么症状| 11月18日是什么星座| 葡萄糖酸钙锌口服溶液什么时候喝| 火鸡是什么鸡| 镜检白细胞是什么意思| 鼠目寸光是什么意思| 三个降号是什么调| 什么是血液病| 打呼噜吃什么药最管用| 佛道是什么意思| 护肝养肝吃什么药最好| 肌酸激酶是什么意思| 梅核气吃什么药能除根| 曲奇饼干为什么不成形| 梅菜是什么菜| 金字旁成是什么字| 百度

The Java Language Environment

Java is Object Oriented

CHAPTER 3

    百度 ”西城法院民一庭庭长郭云燕表示。

  1. My Object All Sublime
  2. I Will Achieve in Time

Gilbert and Sullivan--The Mikado

To stay abreast of modern software development practices, Java is object oriented from the ground up . The point of designing an object-oriented language is not simply to jump on the latest programming fad. The object-oriented paradigm meshes well with the needs of client-server and distributed software. Benefits of object technology are rapidly becoming realized as more organizations move their applications to the distributed client-server model.

Unfortunately, "object oriented" remains misunderstood, over-marketed as the silver bullet that will solve all our software ills, or takes on the trappings of a religion. The cynic's view of object-oriented programming is that it's just a new way to organize your source code. While there may be some merit to this view, it doesn't tell the whole story, because you can achieve results with object-oriented programming techniques that you can't with procedural techniques.

An important characteristic that distinguishes objects from ordinary procedures or functions is that an object can have a lifetime greater than that of the object that created it. This aspect of objects is subtle and mostly overlooked. In the distributed client-server world, you now have the potential for objects to be created in one place, passed around networks, and stored elsewhere, possibly in databases, to be retrieved for future work.

As an object-oriented language, Java draws on the best concepts and features of previous object-oriented languages, primarily Eiffel, SmallTalk, Objective C, and C++. Java goes beyond C++ in both extending the object model and removing the major complexities of C++. With the exception of its primitive data types, everything in Java is an object, and even the primitive types can be encapsulated within objects if the need arises.

3.1 Object Technology in Java

To be truly considered "object oriented", a programming language should support at a minimum four characteristics:

  • Encapsulation--implements information hiding and modularity (abstraction)
  • Polymorphism--the same message sent to different objects results in behavior that's dependent on the nature of the object receiving the message
  • Inheritance--you define new classes and behavior based on existing classes to obtain code re-use and code organization
  • Dynamic binding--objects could come from anywhere, possibly across the network. You need to be able to send messages to objects without having to know their specific type at the time you write your code. Dynamic binding provides maximum flexibility while a program is executing

Java meets these requirements nicely, and adds considerable run-time support to make your software development job easier.

3.2 What Are Objects?

At its simplest, object technology is a collection of analysis, design, and programming methodologies that focuses design on modelling the characteristics and behavior of objects in the real world. True, this definition appears to be somewhat circular, so let's try to break out into clear air.

What are objects? They're software programming models. In your everyday life, you're surrounded by objects: cars, coffee machines, ducks, trees, and so on. Software applications contain objects: buttons on user interfaces, spreadsheets and spreadsheet cells, property lists, menus, and so on. These objects have state and behavior. You can represent all these things with software constructs called objects, which can also be defined by their state and their behavior.

In your everyday transportation needs, a car can be modelled by an object. A car has state (how fast it's going, in which direction, its fuel consumption, and so on) and behavior (starts, stops, turns, slides, and runs into trees).

You drive your car to your office, where you track your stock portfolio. In your daily interactions with the stock markets, a stock can be modelled by an object. A stock has state (daily high, daily low, open price, close price, earnings per share, relative strength), and behavior (changes value, performs splits, has dividends).

After watching your stock decline in price, you repair to the cafe to console yourself with a cup of good hot coffee. The espresso machine can be modelled as an object. It has state (water temperature, amount of coffee in the hopper) and it has behavior (emits steam, makes noise, and brews a perfect cup of java).

3.3 Basics of Objects

Basics of Objects

An object's behavior is defined by its methods. Methods manipulate the instance variables to create new state; an object's methods can also create new objects.

The small picture to the left is a commonly used graphical representation of an object. The diagram illustrates the conceptual structure of a software object--it's kind of like a cell, with an outer membrane that's its interface to the world, and an inner nucleus that's protected by the outer membrane.

An object's instance variables (data) are packaged, or encapsulated, within the object. The instance variables are surrounded by the object's methods. With certain well-defined exceptions, the object's methods are the only means by which other objects can access or alter its instance variables. In Java, classes can declare their instance variables to be public, in which cases the instance variables are globally accessible to other objects. Declarations of accessibility are covered later in Access Specifiers. Later on you will also find a discussion on class variables and class methods.

3.3.1 Classes

A class is a software construct that defines the data (state) and methods (behavior) of the specific concrete objects that are subsequently constructed from that class. In Java terminology, a class is built out of members, which are either fields or methods. Fields are the data for the class. Methods are the sequences of statements that operate on the data. Fields are normally specific to an object--that is, every object constructed from the class definition will have its own copy of the field. Such fields are known as instance variables. Similarly, methods are also normally declared to operate on the instance variables of the class, and are thus known as instance methods.

A class in and of itself is not an object. A class is like a blueprint that defines how an object will look and behave when the object is created or instantiated from the specification declared by the class. You obtain concrete objects by instantiating a previously defined class. You can instantiate many objects from one class definition, just as you can construct many houses all the same 1 from a single architect's drawing. Here's the basic declaration of a very simple class called Point



class Point extends Object {
      public double  x;    /*   instance variable  */
      public double  y;    /*   instance variable  */
}

As mentioned, this declaration merely defines a template from which real objects can be instantiated, as described next.

3.3.2 Instantiating an Object from its Class

Having declared the size and shape of the Point class above, any other object can now create a Point object--an instance of the Point class--with a fragment of code like this:


    
Point  myPoint;           // declares a variable to refer to a Point object
             
myPoint = new Point();   // allocates an instance of  a Point object

Now, you can access the variables of this Point object by referring to the names of the variables, qualified with the name of the object:



myPoint.x = 10.0;
             
myPoint.y = 25.7;

This referencing scheme, similar to a C structure reference, works because the instance variables of Point were declared public in the class declaration. Had the instance variables not been declared public, objects outside of the package within which Point was declared could not access its instance variables in this direct manner. The Point class declaration would then need to provide accessor methods to set and get its variables. This topic is discussed in a little more detail after this discussion on constructors.

3.3.3 Constructors

When you declare a class in Java, you can declare optional constructors that perform initialization when you instantiate objects from that class. You can also declare an optional finalizer, discussed later. Let's go back to our Point class from before:



class Point extends Object {
          public double  x;    /* instance variable  */
          public double  y;   /* instance variable  */
          Point() {        /* constructor to initialize to default zero value<  */
           x = 0.0;
            y = 0.0;
        }                  /* constructor to initialize to specific value  */
         Point(double x, double y) {
            this.x = x;    /* et instance variables to passed parameters  */
        
            this.y = y;
        }
        
    }

Methods with the same name as the class as in the code fragment are called constructors. When you create (instantiate) an object of the Point class, the constructor method is invoked to perform any initialization that's needed--in this case, to set the instance variables to an initial state.

This example is a variation on the Point class from before. Now, when you wish to create and initialize Point objects, you can get them initialized to their default values, or you can initialize them to specific values:


 
Point  lowerLeft;
Point  upperRight;

lowerLeft = new Point();        /* initialize to default zero value  */
upperRight = new Point(100.0, 200.0);  /* initialize to non- zero   */

The specific constructor that's used when creating a new Point object is determined from the type and number of parameters in the new invocation.

The this Variable

What's the this variable in the examples above? this refers to the object you're "in" right now. In other words, this refers to the receiving object. You use this to clarify which variable you're referring to. In the two-parameter Point method, this.x means the x instance variable of this object, rather than the x parameter to the Point method.

In the example above, the constructors are simply conveniences for the Point class. Situations arise, however, where constructors are necessary, especially in cases where the object being instantiated must itself instantiate other objects. Let's illustrate one of those situations by declaring a Rectangle class that uses two Point objects to define its bounds:



class Rectangle extends Object {

private Point lowerLeft;

private Point upperRight;

        Rectangle() {
         lowerLeft = new Point();
         upperRight = new Point();
             
        }
            . . .
     
instance methods appear in here

            . . .
 }

In this example, the Rectangle constructor is vitally necessary to ensure that the two Point objects are instantiated at the time a Rectangle object is instantiated, otherwise, the Rectangle object would subsequently try to reference points that have not yet been allocated, and would fail.

3.3.4 Methods and Messaging

Methods and Messaging

If an object wants another object to do some work on its behalf, then in the parlance of object-oriented programming, the first object sends a message to the second object. In response, the second object selects the appropriate method to invoke. Java method invocations look similar to functions in C and C++.

Using the message passing paradigms of object-oriented programming, you can build entire networks and webs of objects that pass messages between them to change state. This programming technique is one of the best ways to create models and simulations of complex real-world systems. Let's redefine the declaration of the Point class from above such that its instance variables are private, and supply it with accessor methods to access those variables.


   
class Point extends Object {
        
 private double  x;    /* instance variable  */
             
 private double  y;    /* instance variable  */
             

        Point() {    /* constructor to initialize to zero  */
        
            x = 0.0;
            y = 0.0;
        }
                    /* constructor to initialize to specific value  */
           
        Point(double x, double y) {
             
            this.x = x;
             
            this.y = y;
           
        }
          
        public void setX(double x) {    /* accessor method  */
           this.x = x;
        
        }
        public void setY(double y) {    /* accessor method  */
        
            this.y = y;
            
        }
          
        public double getX() {    /*  accessor method  */
          
            return x;
      
        }
          
        public double getY() {    /*  accessor method  */
            
            return y;
            
        }
           
    }

These method declarations provide the flavor of how the Point class provides access to its variables from the outside world. Another object that wants to manipulate the instance variables of Point objects must now do so via the accessor methods:


    
Point  myPoint;          //  declares a variable to refer to a Point object
              
myPoint = new Point();   //  allocates an instance of  a Point object

    
myPoint.setX(10.0);      //  sets the x variable via the accessor method

myPoint.setY(25.7);

Making instance variables public or private is a design tradeoff the designer makes when declaring the classes. By making instance variables public, you expose details of the class implementation, thereby providing higher efficiency and conciseness of expression at the possible expense of hindering future maintenance efforts. By hiding details of the internal implementation of a class, you have the potential to change the implementation of the class in the future without breaking any code that uses that class.

3.3.5 Finalizers

You can also declare an optional finalizer that will perform necessary teardown actions when the garbage collector is about to free an object. This code fragment illustrates a finalize method in a class.


    
/*** Close the stream when garbage is collected.*/  
             
    protected void finalize() {
          
        try {
             
            file.close();
              
        } catch (Exception e) {
            
        }
           
    }

This finalize method will be invoked when the object is about to be garbage collected, which means that the object must shut itself down in an orderly fashion. In the particular code fragment above, the finalize method merely closes an I/O file stream that was used by the object, to ensure that the file descriptor for the stream is closed.

3.3.6 Subclasses

Subclasses are the mechanism by which new and enhanced objects can be defined in terms of existing objects. One example: a zebra is a horse with stripes. If you wish to create a zebra object, you notice that a zebra is kind of like a horse, only with stripes. In object-oriented terms, you'd create a new class called Zebra, which is a subclass of the Horse class. In Java language terms, you'd do something like this:


    
class Zebra extends Horse {
   
      Your new instance variables and new methods go here
               
 }
            

The definition of Horse, wherever it is, would define all the methods to describe the behavior of a horse: eat, neigh, trot, gallop, buck, and so on. The only method you need to override is the method for drawing the hide. You gain the benefit of already written code that does all the work--you don't have to re-invent the wheel, or in this case, the hoof. The extends keyword tells the Java compiler that Zebra is a subclass of Horse. Zebra is said to be a derived class--it's derived from Horse, which is called a superclass.

Here's an example of making a subclass, which is a variant of our Point class from previous examples to create a new three-dimensional point called ThreePoint:


 
class Point extends Object {
      
        protected double  x;    /* instance variable  */
            
        protected double  y;    /* instance variable  */
             

        Point() {    /* constructor to initialize to zero  */
            
            x = 0.0;
             
            y = 0.0;
             
        }
           
    }

    
class ThreePoint extends Point {
           
        protected double z;    /* the z coordinate of the point  */
            
        ThreePoint() {      /* default constructor  */
              
            x = 0.0;        /* initialize the coordinates  */
             
            y = 0.0;
             
            z = 0.0;
              
        }
             
        ThreePoint(double x, double y, double z) {/* specific constructor */
            
            this.x = x;        / *initialize the coordinates  */
              
            this.y = y;
              
            this.z = z;
             
        }
              
    }

Notice that ThreePoint adds a new instance variable for the z coordinate of the point. The x and y instance variables are inherited from the original Point class, so there's no need to declare them in ThreePoint. However, notice we had to make Point's instance variables protected instead of private as in the previous examples. Had we left Point's instance variables private, even its subclasses would be unable to access them, and the compilation would fail.

Subclasses enable you to use existing code that's already been developed and, much more important, tested, for a more generic case. You override the parts of the class you need for your specific behavior. Thus, subclasses gain you reuse of existing code--you save on design, development, and testing. The Java run-time system provides several libraries of utility functions that are tested and are also thread safe.

All classes in Java ultimately inherit from Object. Object is the most general of all the classes. New classes that you declare add functionality to their superclasses. The further down the class hierarchy you go--that is, the further you get from Object--the more specialized your classes become.

Single Inheritance and the Class Hierarchy

Java implements what is known as a single-inheritance model. A new class can subclass ( extend, in Java terminology) only one other class. Ultimately, all classes eventually inherit from the Object class, forming a tree structure with Object as its root. This picture illustrates the class hierarchy of the classes in the Java utility package, java.util.

The HashTable class is a subclass of Dictionary, which in turn is a subclass of Object. Dictionary inherits all of Object's variables and methods (behavior), then adds new variables and behavior of its own. Similarly, HashTable inherits all of Object's variables and behavior, plus all of Dictionary's variables and behavior, and goes on to add its own variables and behavior.

Then the Properties class subclasses HashTable in turn, inheriting all the variables and behavior of its class hierarchy. In a similar manner, Stack and ObserverList are subclasses of Vector, which in turn is a subclass of Object. The power of the object-oriented methodology is apparent--none of the subclasses needed to re-implement the basic functionality of their superclasses, but needed only add their own specialized behavior.

Single Inheritance and the Class Hierarchy

However, the above diagram points out the minor weakness with the single-inheritance model. Notice that there are two different kinds of enumerator classes in the picture, both of which inherit from Object. An enumerator class

implements behavior that iterates through a collection, obtaining the elements of that collection one by one. The enumerator classes define behavior that both HashTable and Vector find useful. Other, as yet undefined collection classes, such as list or queue, may also need the behavior of the enumeration classes. Unfortunately, they can inherit from only one superclass.

A possible method to solve this problem would be to enhance some superclass in the hierarchy to add such useful behavior when it becomes apparent that many subclasses could use the behavior. Such an approach would lead to chaos and bloat. If every time some common useful behavior were required for all subsequent subclasses, a class such as Object would be undergoing constant modification, would grow to enormous size and complexity, and the specification of its behavior would be constantly changing. Such a "solution" is untenable. The elegant and workable solution to the problem is provided via Java interfaces, the subject of the next topic.

3.3.7 Java Language Interfaces

Interfaces were introduced to Java to enhance Java's single-inheritance model. The designers of Java decided that multiple inheritance created too many problems for programmers and compiler writers, and decided that a single inheritance model was better overall. Some of the problems described in the previous discussion on the single-inheritance model are solved in a more elegant fashion by the use of interfaces.

An interface in the Java language is simply a specification of methods that an object declares it implements. An interface does not include instance variables or implementation code--only declarations of constants and methods. The concept of an interface in the Java language was borrowed from the Objective-C concept of a protocol.

Whereas a class can inherit from only one superclass, a class can implement as many interfaces as it chooses to. Using the examples from the previous discussion, the HashTableEnumerator and VectorEnumerator classes both implement an Enumeration interface that's specific to the characteristics of the HashTable and Vector classes. When you define a new collection class--a Queue class, for instance--you'll also probably define a QueueEnumerator class that implements the Enumeration interface.

The concept of the interface is powerful--classes that implement a given interface need do so only at the appropriate level in the class hierarchy. This picture illustrates the use of interfaces.

Java Language Interfaces

In this illustration, interfaces are represented by rectangles. You see that the Cloneable interface is implemented by multiple classes. In addition, the HashtableEnumerator and the VectorEnumerator classes both implement the Enumeration interface. Any given class can implement as many interfaces as it wants to, and in any way that it wants to. Details of the actual implementation of the interface are hidden within the class definition, and should be replaceable without affecting the outside view of the interface in any way. Recall, however, that an interface merely declares methods; it does not

implement them. When inheriting from classes (in languages such as C++), the implementation of inherited classes is also inherited, so more code can be reused when compared to the amount of code re-use in multiply-inherited interfaces. For this reason, inheriting from interfaces provides a reasonable alternative to multiple inheritance, but this practice should not be seen as a substitute for the more powerful but often confusing practice of inheriting from multiple classes.

3.3.8 Access Control

When you declare a new class in Java, you can indicate the level of access permitted to its members--that is, its instance variables and methods. Java provides four levels of access. Three of the levels must be explicitly specified: public, protected, and private. Members declared public are available to any other class anywhere. Members declared protected are accessible only to subclasses of that class, and nowhere else. Members declared private are accessible only from within the class in which they're declared--they're not available even to their subclasses.

The fourth access level doesn't have a name--it's often called "friendly" and is the access level you obtain if you don't specify otherwise. The "friendly" access level indicates that the class's members are accessible to all objects within the same package, but inaccessible to objects outside the package. Packages, a useful tool for grouping together related collections of classes and interfaces, are discussed below.

3.3.9 Packages

Java packages are collections of classes and interfaces that are related to each other in some useful way. Such classes need to be able to access each other's instance variables and methods directly. A geometry package consisting of Point and Rectangle classes, for instance, might well be easier and cleaner to implement--as well as more efficient--if the Point's instance variables were directly available to the Rectangle class. Outside of the geometry package, however, the details of implementations are hidden from the rest of the world, giving you the freedom to changed implementation details without worrying you'll break code that uses those classes. Packages are created by storing the source files for the classes and interfaces of each package in a separate directory in the file system.

The primary benefit of packages is the ability to organize many class definitions into a single unit. For example, all the Java I/O system code is collected into a single package called java.io. The secondary benefit from the programmer's viewpoint is that the "friendly" instance variables and methods are available to all classes within the same package, but not to classes defined outside the package.

3.3.10 Class Variables and Class Methods

Java follows conventions from other object-oriented languages in providing class methods and class variables. Normally, variables you declare in a class definition are instance variables--there is one of those variables in every separate object created (instantiated) from the class. A class variable, on the other hand, is local to the class itself--there's only a single copy of the variable and it's shared by every object you instantiate from the class.

To declare class variables and class methods in Java programs, you declare them static. This short code fragment illustrates the declaration of class variables:



class Rectangle extends Object {
        
        static  final int version = 2;
            
        static  final int revision = 0;
             
    }

The Rectangle class declares two static variables to define the version and revision level of this class. Now, every instance of Rectangle you create from this class will share these same variables. Notice they're also defined as final because you want them to be constants.

Class methods are common to an entire class. When would you use class methods? Usually, when you have behavior that's common to every object of a class. For example, suppose you have a Window class. A useful item of information you can ask the class is the current number of currently open windows. This information is shared by every instance of Window and it is only available through knowledge obtained from other instances of Window. For these reasons, it is necessary to have just one class method to return the number of open windows.

In general, class methods can operate only on class variables. Class methods can't access instance variables, nor can they invoke instance methods. Like class variables, you declare class methods by defining them as static.

We say, "in general", because you could pass an object reference to a class method, and the class method could then operate on the object's public instance variables, and invoke the object's instance methods via the reference. However, you're usually better off doing only class-like operations at the class level, and doing object-like operations at the object level.

3.3.11 Abstract Methods

Abstract methods are a powerful construct in the object-oriented paradigm. To understand abstract methods, we look at the notion of an abstract superclass. An abstract superclass is a class in which you declare methods that aren't actually implemented by that class--they only provide place-holders that subsequent subclasses must override and supply their actual implementation.

This all sounds wonderfully, well, abstract, so why would you need an abstract superclass? Let's look at a concrete example, no pun intended. Let's suppose you're going to a restaurant for dinner, and you decide that tonight you want to eat fish. Well, fish is somewhat abstract--you generally wouldn't just order fish; the waiter is highly likely to ask you what specific kind of fish you want. When you actually get to the restaurant, you will find out what kind of fish they have, and order a specific fish, say, sturgeon, or salmon, or opakapaka.

In the world of objects, an abstract class is like generic fish--the abstract class defines generic state and generic behavior, but you'll never see a real live implementation of an abstract class. What you will see is a concrete subclass of the abstract class, just as opakapaka is a specific (concrete) kind of fish.

Suppose you are creating a drawing application. The initial cut of your application can draw rectangles, lines, circles, polygons, and so on. Furthermore, you have a series of operations you can perform on the shapes--move, reshape, rotate, fill color, and so on. You could make each of these graphic shapes a separate class--you'd have a Rectangle class, a Line class, and so on. Each class needs instance variables to define its position, size, color, rotation and so on, which in turn dictates methods to set and get at those variables.

At this point, you realize you can collect all the instance variables into a single abstract superclass called Graphical, and implement most of the methods to manipulate the variables in that abstract superclass. The skeleton of your abstract superclass might look something like this:



abstract class Graphical extends Object {
              
    protected Point lowerLeft;     // lower left of bounding box
               
    protected Point upperRight;    // upper right of bounding box
                                   
               . . .
            
   more instance variables
               
              . . .
              
    public void setPosition(Point ll, Point ur) {
            
        lowerLeft = ll;
             
        upperRight = ur;
             
    }
            
    abstract void drawMyself();   // abstract method
               
}

Now, you can't instantiate the Graphical class, because it's declared abstract. You can only instantiate a subclass of it. You would implement the Rectangle class or the Circle class as a subclass of Graphical. Within Rectangle, you'd provide a concrete implementation of the drawMySelf method that draws a rectangle, because the definition of drawMySelf must by necessity be unique to each shape inherited from the Graphical class. Let's see a small fragment of the Rectangle class declaration, where its drawMySelf method operates in a somewhat PostScript'y fashion:



class Rectangle extends Graphical {
           
    void drawMySelf() {         // really does the drawing
         

     moveTo(lowerLeft.x, lowerLeft.y);
         
     lineTo(upperRight.x, lowerLeft.y);
             
     lineTo(upperRight.x, upperRight.y)
            
      lineTo(lowerLeft.x, upperRight.y);
             
                     . . .
          
            and so on and so on
                
                     . . .
            
    }
            
}

Notice, however, that in the declaration of the Graphical class, the setPosition method was declared as a regular ( public void) method. All methods that can be implemented by the abstract superclass can be declared there and their implementations defined at that time. Then, every class that inherits from the abstract superclass will also inherit those methods.

You can continue in this way adding new shapes that are subclasses of Graphical, and most of the time, all you ever need to implement is the methods that are unique to the specific shape. You gain the benefit of re-using all the code that was defined inside the abstract superclass.

3.4 Summary

This chapter has conveyed the essential aspects of Java as an object-oriented language. To sum up:

  • Classes define templates from which you instantiate (create) distinct concrete objects.
  • Instance variables hold the state of a specific object.
  • Objects communicate by sending messages to each other. Objects respond to messages by selecting a method to execute.
  • Methods define the behavior of objects instantiated from a class. It is an object's methods that manipulate its instance variables. Unlike regular procedural languages, classes in an object-oriented language may have methods with the same names as other classes. A given object responds to a message in ways determined by the nature of that object, providing polymorphic behavior.
  • Subclasses provide the means by which a new class can inherit instance variables and methods from any already defined class. The newly declared class can add new instance variables (extra state), can add new methods (new behavior), or can override the methods of its superclass (different behavior). Subclasses provide code reuse.

Taken together, the concepts of object-oriented programming create a powerful and simple paradigm for software developers to share and re-use code and build on the work of others.

梦见卖鱼是什么意思 中间细胞百分比偏高是什么意思 刮宫后需要注意什么 筋膜刀是什么 太阳花什么时候开花
木石念什么 身上长瘊子是什么原因 香菜什么时候种植最好 黄疸肝炎有什么症状 羊胡子疮用什么药膏
什么头蛇尾 四百分能上什么大学 干支是什么意思 拔了牙可以吃什么 牵牛花是什么颜色的
梦见驴是什么意思 十二生肖排第一是什么生肖 兔和什么属相最配 音字五行属什么 金桔什么时候开花结果
子宫囊肿是什么原因引起的hcv8jop9ns8r.cn 穿模是什么意思shenchushe.com 农历什么意思hcv9jop3ns3r.cn 屁是什么气体hcv9jop7ns0r.cn 唯有女子与小人难养也什么意思xinmaowt.com
坐月子什么不能吃hcv8jop6ns2r.cn 孕妇胆固醇高对胎儿有什么影响hcv8jop6ns9r.cn 忧心忡忡是什么意思hcv8jop2ns7r.cn 牛肉和什么包饺子好吃hcv8jop0ns1r.cn 什么杀精子最厉害beikeqingting.com
脚背痒是什么原因hcv8jop9ns7r.cn 腱鞘囊肿是什么原因引起的hcv8jop6ns5r.cn 副作用是什么意思gysmod.com 排卵期同房后要注意什么hcv7jop6ns7r.cn 小孩内热吃什么药hcv8jop5ns8r.cn
中医学专业学什么hcv7jop6ns8r.cn 方圆是什么意思hcv8jop8ns0r.cn 朋友圈为什么发不出去onlinewuye.com hpv检查前需要注意什么hcv8jop4ns8r.cn 子宫内膜增厚有什么影响hcv9jop6ns1r.cn
百度