aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes JDK violating Encapsulation ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "JDK violating Encapsulation ?" Watch "JDK violating Encapsulation ?" New topic
Author

JDK violating Encapsulation ?

Rushabh Shah
Greenhorn

Joined: Mar 29, 2004
Posts: 18

How do you get the no. of elements in an Array. array.length, length is a variable of Array class? And surprisingly its a public variable, violating one of the paradigms of OO, Encapsulation. Though you cannot tamper with its value since its marked final.

Why the Java guys chose to expose variable instead of a length() method (like String) ?
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14266
    
  21

An array is an object, but it is not an instance of class Array. The 'length' property of an array is not a public member variable of class Array.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Omar Al Kababji
Ranch Hand

Joined: Jan 13, 2009
Posts: 357
Arrays are special in Java, they are a bit twisted because of performance reasons, the same as having primitive types which are not 100% OO. sometimes you need to compromise between two things, OO and performance.

Take another example far from java, in theory a DB must be normalized however in real life sometimes you have to ignore normalization for performance reasons.


Omar Al Kababji - Electrical & Computer Engineer
[SCJP - 90% - Story] [SCWCD - 94% - Story] [SCBCD - 80% - Story] | My Blog
Rushabh Shah
Greenhorn

Joined: Mar 29, 2004
Posts: 18
Omar Al Kababji wrote:Arrays are special in Java, they are a bit twisted because of performance reasons, the same as having primitive types which are not 100% OO. sometimes you need to compromise between two things, OO and performance.

Take another example far from java, in theory a DB must be normalized however in real life sometimes you have to ignore normalization for performance reasons.



I get that, but a getter for length would not have affected performance in any means. Like we have for String.
Nitish Bangera
Ranch Hand

Joined: Jul 15, 2009
Posts: 537

There is a getter method for length in java.lang.reflect.Array package. This is a static method. static int getLength(Object array).

int[] a = new int[3]; Array.getLength(a);(import java.lang.reflect.Array). Well its normally not used as length is readily available gives the length of the array.


[ SCJP 6.0 - 90% ] , JSP, Servlets and Learning EJB.
Try out the programs using a TextEditor. Textpad - Java 6 api
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: JDK violating Encapsulation ?