I wanted to ask that what is the default access specifiers/modifiers for an array in java?
For example if I write
int arr[];
What will it be by default?
Is it public abstract final or public by default?
I am asking this question because I am unable to understand comment made by Tom Ball.
I found why default serialVersionUIDs for arrays were different. That calculation includes the class's modifiers, and it turns out all arrays are "public abstract final", not "public" (a new "gotcha" Java interview question :-). Changing that in the runtime, and now all arrays have the same UIDs, even different object classes.
Here is the link https://groups.google.com/d/msg/j2objc-discuss/1zCZYvxBGhY/ZpIRKPLFBgAJ
Can Someone explain?
When you write a declaration like
int arr[];
you are declaring a variable. This variable has exactly those access modifiers, you are declaring. If you don’t specify any modifiers on a class variable, it will be package-private by default. Note that variables can never be abstract.
The reason why you don’t understand the cited text is, that you are confusing the class modifiers of the variable’s type with the variable’s modifiers.
Letting arrays aside, if you declare a variable like Foo bar, then the class Foo has modifiers independently of the modifiers of the variable bar.
Now, the same applies for array types. In Java, arrays are objects, hence have a class type. At runtime, you may invoke getClass() on an array just like on any other object and you will get a Class object representing a synthetic class. You can also access an array class via class literal:
Class<?> clazz=int[].class; // int[]
int mod=clazz.getModifiers();
if(Modifier.isPublic(mod)) System.out.print("public ");
if(Modifier.isAbstract(mod)) System.out.print("abstract ");
if(Modifier.isFinal(mod)) System.out.print("final ");
System.out.print(clazz);
System.out.print(" implements");
for(Class<?> cl:clazz.getInterfaces())
System.out.print(" "+cl.getName());
System.out.println();
It will print
public abstract final class [I implements java.lang.Cloneable java.io.Serializable
showing that the class representing the array type int[] has the special name [I and the modifiers abstract and final, a combination that is impossible for ordinary classes.
Note that an array class is public, if either it’s an array of primitive values or its element type is public as well. As explained, this doesn’t stop you from declaring non-public variables of such a type.
The post that you linked refers to the access modifiers of the (dynamically created, synthetic) class object that represents the array: int[].class in your case.
There is no relation between the modifiers of a class and the modifiers of a field.
Think of it like this: the class java.lang.String is public, but you are free to make a private field of type String.
Related
I have some confusion on what class name to use from the documentation.
If I want to use the method getLength(Object name) from the Array class the compiler accepts java.lang.reflect.Array.getLength(nameOfArray) but not java.lang.Object.getLength(nameOfArray). Though the picture of the API documentation linked below seems to imply to me that both classes are linked to the Array classes method.
Java API documentation example
The reason you see them linked is that Object is a Superclass of Array.
In Java, Object is the superclass of all classes.
The Object class, in the java.lang package, sits at the top of the
class hierarchy tree. Every class is a descendant, direct or indirect,
of the Object class.
More over here: https://docs.oracle.com/javase/tutorial/java/IandI/objectclass.html
Each such child class (Array class in this case) inherits some methods from the superclass (Object class in this case).
If the child class wishes to change any of these variables or methods that it inherits from the superclass, then it will override those. In addition, the child class itself may have its own variables and methods which have got nothing to do with the superclass. That is the case in the example you've shown i.e. Array is a data-structure that has a length, but its parent Object does not have a length.
Note: Please read about Inheritance in Java.
In addition, also read about access specifiers (because private members are not inherited), keywords (eg. final variables can't change value, final methods cannot be overriden, final classes can't be subclassed). Good luck!
If I want to use the method getLength(Object name) from the Array class the compiler accepts java.lang.reflect.Array.getLength(nameOfArray)
Correct, because that's where the method is.
but not java.lang.Object.getLength(nameOfArray).
Incorrect, because there is no such method in the java.lang.Object class.
Though the API documentation linked below seems to imply to me that both class paths are linked to the Array classes method.
No it doesn't. The meaning of the part in your picture is that the second class extends the first class.
That documentation example shows that Array is a child of Object, not that you can use them interchangably.
Array extends Object. It means that Any method available for object is available for an Array, but the inverse is not true.
Consider this example. replace Array with Student and Object with Human. Student extends Human. Lets say that Human has getDateOfBirth method. Student also has getGrades method. On Student you can call getDateOfBirth and getGrades, while on Human you can only call getDateOfBirth because grades are not defined for babies.
Note that Object is the superclass of all other classes. As a result it has least number of methods.
Is it possible to change the value of variables in an interface class using XmlDecoder and XmlEncoder?.
I have an interface class that contains variables that needs to be implemented by other classes. however the value of these variables needs to be changed after some time.
I have an interface class the contains variables that needs to be implemented by other classes.
Interfaces can't contain variables as such - they can only contain constants, so it makes no sense to try to change the value of them.
From JLS 9.3:
Every field declaration in the body of an interface is implicitly public, static, and final.
Your interface should contain appropriate getters/setters instead - or have an abstract superclass which contains the appropriate fields.
I read that to get length of an array, I use the length attribute, like arrayName.length. What is an attribute? Is it a class?
An attribute is another term for a field. It's typically a public constant or a public variable that can be accessed directly. In this particular case, the array in Java is actually an object and you are accessing the public constant value that represents the length of the array.
A class is an element in object oriented programming that aggregates attributes(fields) - which can be public accessible or not - and methods(functions) - which also can be public or private and usually writes/reads those attributes.
so you can have a class like Array with a public attribute lengthand a public method sort().
Attribute is a public variable inside the class/object. length attribute is a variable of int type.
Attributes is same term used alternativly for properties or fields or data members or class members.
An attribute is an instance variable.
In this context, "attribute" simply means a data member of an object.
Attribute is a synonym of field for array.length
Attributes are also data members and properties of a class. They are Variables declared inside class.
A class contains data field descriptions (or properties, fields, data members, attributes), i.e., field types and names, that will be associated with either per-instance or per-class state variables at program run time.
An abstract class is a type of class that can only be used as a base class for
another class; such thus cannot be instantiated. To make a class abstract,
the keyword abstract is used. Abstract classes may have one or more
abstract methods that only have a header line (no method body). The method
header line ends with a semicolon (;). Any class that is derived from the base
class can define the method body in a way that is consistent with the header
line using all the designated parameters and returning the correct data type
(if the return type is not void). An abstract method acts as a place holder; all
derived classes are expected to override and complete the method.
Example in Java
abstract public class Shape
{
double area;
public abstract double getArea();
}
■ What is an attribute?
– A variable that belongs to an object.Attributes is same term used alternatively for properties or fields or data members or class members
■ How else can it be called?
– field or instance variable
■ How do you create one? What is the syntax?
– You need to declare attributes at the beginning of the class definition, outside of any method. The syntax is the following:
;
In java document, it is said :
Unlike interfaces, abstract classes
can contain fields that are not
static and final, and they can contain
implemented methods.
Is that a correct text? that not part confuses me because interfaces don't have static or final fields, right?
Source : http://download.oracle.com/javase/tutorial/java/IandI/abstract.html
Thanks.
Edit :
public interface GroupedInterface extends Interface1,
Interface2, Interface3 {
// constant declarations
double E = 2.718282; // base of natural logarithms
// method signatures
void doSomething (int i, double x);
int doSomethingElse(String s);
}
An interface can contain constant
declarations in addition to method
declarations. All constant values
defined in an interface are implicitly
public, static, and final. Once again,
these modifiers can be omitted.
Every field declaration in the body of
an interface is implicitly public,
static, and final. It is permitted to
redundantly specify any or all of
these modifiers for such fields.
from section 9.3 of the Java Language Specification (here)
Click on "Defining an Interface" on the link in your question:
An interface can contain constant
declarations in addition to method
declarations. All constant values
defined in an interface are implicitly
public, static, and final. Once again,
these modifiers can be omitted.
That is the correct text.
All fields in an interface are inferred to be public, static and final, whether or not explicitly so declared. Just as all methods are public and abstract, whether or not so declared.
the think is.. all fields inside an interface will be static and final, even if you didnt write the static and final!
The documentation is correct. Interfaces may contain static final fields to be used as constants. Abstract classes may contain instance variables to be inherited by extending classes. Those variables are then available in instances of the extending classes.
The quote is correct. Interfaces can have static final fields, but cannot have any other combination (non-static or non-final).
Fields on an interface are static and final by default, adding the modifiers is not necessary because there's no alternative.
For an abstract class it can make sense to give it mutable state, see java.util.AbstractList. Interfaces are not allowed to have any member that would confer mutable state on a class implementing it.
As we use "default" keyword as a access specifier, and it can be used in switch statements as well with complete different purpose, So i was curious that is there any other keywords in java which can be used in more then one purposes
The "default" in the case of access modifier isn't a keyword - you don't write:
default void doSomething()
However, when specifying the default value of an attribute of annotations - it is.
switch (a) {
default: something();
}
and
public #interface MyAnnotation {
boolean bool() default true;
}
That, together with final as pointed out by Jon Skeet seems to cover everything. Perhaps except the "overloaded" for keyword:
for (initializer; condition; step) and for (Type element : collection)
You can't use default as an access specifier, so I don't think even that counts. (EDIT: As Bozho pointed out, it can be used in annotations.)
final means "can't be derived from / overridden" and "is read-only" which are two different - but related - meanings.
default can be used both in a switch and as a default value in an annotation (as pointed out by Bozho)
final means "can't be derived from / overridden" and "is read-only" which are two different - but related - meanings (as pointed out by Jon)
extends can be used both to specify the supertype of a class and can be used in wildcards and type variables to put a constraint (related but not exactly the same) (List<? extends Foo>)
super can be used to specify to something in a superclass of the current class, or in a wildcard to put a constraint (List<? super Foo>)
static means both "part of the class, not an instance" (for methods, attributes or initializers) and as a static import
class to declare a class (class Foo {}), or to refer to a class literal (Foo.class) (as answered by ILMTitan)
(for can be used in a normal for loop and the "enhanced" for, but that's more like overloading (as Bozho puts it so nicely) than really having two meanings)
Something no one else has mentioned yet: the class keyword has two different uses.
Declaring a class:
class Test{};
and indicating a class literal:
Class<Test> testClass = Test.class;
The final keyword can mean different things.
When modifying classes is means that the class cannot be subclassed.
When modifying a method, it means that the method cannot be Overridden.
When modifying a variable, it means that the variable cannot point to any other variable.
The default keyword is not used as an access specifier. The absence of private, protected and public means use of default.
Example:
class Test { // default access for class.
int A; // default access for the class member.
}
Some examples of Java keywords which find different use are:
final : A final class cannot be subclassed, a final method cannot be overridden, and a final variable can occur at most once as a left-hand expression.
Super: Used to access members of a class inherited by the class in which it appears, also used to forward a call from a constructor to a constructor in the superclass.
Static: Used to create static initialization blocks, also static members and static imports.
for:Used for the conventional for loop and the newer Java 1.5 enhanced for loop.
The static keyword associates methods and fields with a class instead of instances of that class, but it's also used to signify static initialization sections as in:
public class MyClass
{
private static int a;
static
{
a = 1;
}
public static void doSomethingCool()
{
...
}
}
Pascal's comment reminded me of static imports:
import static MyClass.doSomethingCool;
public class MyOtherClass
{
public void foo()
{
// Use the static method from MyClass
doSomethingCool();
}
}
I gave a look at java keywords but it seems that keywords are unique.. you can check yourself.
By the way default can't used as an access specifier, it's inherited when noone is specified.
Do we really use default as an access specifier? No specifier at all is "default". But you don't use the keyword that way.
final has different uses:
in a variable declaration it means a variable can't be changed.
In a method signature it means a method can't be overridden
In a parameter list it means a variable can't be altered in a method.
The "extends" keyword can be for single inheritance (either implementation or "pure abstract class" aka "interface inheritance" in Java).
The "extends" keyword can also be used for multiple (interface) inheritance.
The ones who always argue that Java doesn't support multiple inheritance will hence have a hard time arguing that "extends" in those two cases is doing exactly the same thing.
Now I'm in the other camp: I consider that multiple interface inheritance is multiple inheritance and that implementation inheritance is just an OOP detail (that doesn't exist at the OOA/OOD level) and hence I consider that "extends" is really doing the same thing in both case and that hence my answer doesn't answer the question :)
But it's an interesting keyword nonetheless :)
You can think of the following things
Default
final
super
":" (colon) used at different places , which has a different meaning at different places
As all the other answers have stated, there are many keywords that server multiple purposes depending on context. I just wanted to add that there is a reason for this: There is a strong aversion to adding keywords because such additions break existing code, so when new features are added existing keywords are used if they make a reasonable fit, such as super and extends for generics and default for annotations, or they are just skipped as in the colon used in the enhanced for loop.
So my point is to expect that as the language continues to evolve even more uses are found for existing keywords rather than introducing new ones.
BTW there is no such thing as an access specifier in Java. The term in the JLS is 'access modifier'.