• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JDK violating Encapsulation ?

 
Rushabh Shah
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Posts: 15627
46
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Omar Al Kababji
Ranch Hand
Posts: 357
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
Rushabh Shah
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 537
Eclipse IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic