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:
;
Related
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.
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 was wondering if it's possible to use a variable of a java class in another java class.Suppose variable Time is defined and calculated in Class A, how can I use it in Class B?
Other answers have suggested increasing a variable's visibility. Don't do this. It breaks encapsulation: the fact that your class uses a field to store a particular piece of information is an implementation detail; you should expose relevant information via the class's API (its methods) instead. You should make fields private in almost all cases.
Likewise, some other answers have suggested possibly making the variable static. Don't do this arbitrarily. You need to understand what static really means: it's saying that this piece of information is related to the type rather than to any one particular instance of the type. Occasionally that's appropriate, but it's generally a road towards less testable code - and in many cases it's clearly wrong. For example, a Person class may well have a name variable, but that certainly shouldn't be static - it's clearly a piece of information about a single person.
You should think carefully before exposing information anyway - consider whether there's a wider operation which the class in question could expose, instead of just giving away its data piecemeal - but when you do want to expose a field's value, use a property. For example:
public class Person {
private final String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
By exposing it via a method, you can later change the implementation details without breaking existing clients.
Then from another class, you'd just call the getName() method:
// However you end up getting a reference to an instance of Person
Person person = ...;
String name = person.getName();
If you do have a static field, you can expose the value in the same way, but with a static method, which you'd call using the class name.
Be careful about returning values which are mutable, e.g. java.util.Date. This is another reason for using a getter method instead of allowing direct access to the field - you can make the method return a defensive copy where you need to.
If it is declared as public, you may use ClassA.yourVariable. On the other hand, for private access modifier, include the getter to your ClassA. On the ClassB, call ClassA.getYourVariable().
Also read about access specifiers in Java it might help.
If the variable is static, you can refer to it as A.Time from any code that has access to the variable. There's only one Time value for all of class A. If it is an instance variable, and you have an instance a of class A, you can refer to the variable as a.Time. There's a separate value for each instance of class A.
This is subject to Java's access rules:
if the field is public, any code can access it (this makes public variables kind of dangerous unless they are also declared final)
if the field is protected, only code in the same package or in a subclass of A can access it
if the field has default access, only code in the same package as class A can access it
if the field is private, only code in class A (including inner classes of A) can access it.
Alternatively, you can provide an accessor method in class A:
public class A {
. . .
public class getTime() {
return this.Time; // the "this." is optional
}
}
If you declare your Variable as public or static you will be able to access it from another class.
WHICH IS A VERY VERY BAD IDEA :)
When referring to internal private variables of Java POJOs that have getters/setters, I've used the following terms:
field
variable
attribute
property
Is there any difference between the above? If so, what is the correct term to use? Is there a different term to use when this entity is persisted?
From here: http://docs.oracle.com/javase/tutorial/information/glossary.html
field
A data member of a class. Unless specified otherwise, a field is not static.
property
Characteristics of an object that users can set, such as the color of a window.
attribute
Not listed in the above glossary
variable
An item of data named by an identifier. Each variable has a type, such as int or Object, and a scope. See also class variable, instance variable, local variable.
Yes, there is.
Variable can be local, field, or constant (although this is technically wrong). It's vague like attribute. Also, you should know that some people like to call final non-static (local or instance) variables
"Values". This probably comes from emerging JVM FP languages like Scala.
Field is generally a private variable on an instance class. It does not mean there is a getter and a setter.
Attribute is a vague term. It can easily be confused with XML or Java Naming API. Try to avoid using that term.
Property is the getter and setter combination.
Some examples below
public class Variables {
//Constant
public final static String MY_VARIABLE = "that was a lot for a constant";
//Value
final String dontChangeMeBro = "my god that is still long for a val";
//Field
protected String flipMe = "wee!!!";
//Property
private String ifYouThoughtTheConstantWasVerboseHaHa;
//Still the property
public String getIfYouThoughtTheConstantWasVerboseHaHa() {
return ifYouThoughtTheConstantWasVerboseHaHa;
}
//And now the setter
public void setIfYouThoughtTheConstantWasVerboseHaHa(String ifYouThoughtTheConstantWasVerboseHaHa) {
this.ifYouThoughtTheConstantWasVerboseHaHa = ifYouThoughtTheConstantWasVerboseHaHa;
}
}
There are many more combinations, but my fingers are getting tired :)
If your question was prompted by using JAXB and wanting to choose the correct XMLAccessType, I had the same question. The JAXB Javadoc says that a "field" is a non-static, non-transient instance variable. A "property" has a getter/setter pair (so it should be a private variable). A "public member" is public, and therefore is probably a constant. Also in JAXB, an "attribute" refers to part of an XML element, as in <myElement myAttribute="first">hello world</myElement>.
It seems that a Java "property," in general, can be defined as a field with at least a getter or some other public method that allows you to get its value. Some people also say that a property needs to have a setter. For definitions like this, context is everything.
Dietel and Dietel have a nice way of explaining fields vs variables.
“Together a class’s static variables and instance variables are known as its fields.” (Section 6.3)
“Variables should be declared as fields only if they’re required for use in more than one method of the class or if the program should save their values between calls to the class’s methods.” (Section 6.4)
So a class's fields are its static or instance variables - i.e. declared with class scope.
Reference - Dietel P., Dietel, H. - Java™ How To Program (Early Objects), Tenth Edition (2014)
If you take clue from Hibernate:
Hibernate reads/writes Object's state with its field.
Hibernate also maps the Java Bean style properties to DB Schema.
Hibernate Access the fields for loading/saving the object.
If the mapping is done by property, hibernate uses the getter and setter.
It is the Encapsulation that differentiates means where you have getter/setters for a field and it is called property, withthat and we hide the underlying data structure of that property within setMethod, we can prevent unwanted change inside setters. All what encapsulation stands for...
Fields must be declared and initialized before they are used. Mostly for class internal use.
Properties can be changed by setter and they are exposed by getters. Here field price has getter/setters so it is property.
class Car{
private double price;
public double getPrice() {…};
private void setPrice(double newPrice) {…};
}
<class name="Car" …>
<property name="price" column="PRICE"/>
</class>
Similarly using fields, [In hibernate it is the recommended way to MAP using fields, where private int id; is annotated #Id, but with Property you have more control]
class Car{
private double price;
}
<class name="Car">
<property name=" price" column="PRICE" access="field"/>
</class>
Java doc says:
Field is a data member of a class. A field is non static, non-transient instance variable.
Field is generally a private variable on an instance class.
The difference between a variable, field, attribute, and property in Java:
A variable is the name given to a memory location. It is the basic unit of storage in a program.
A field is a data member of a class. Unless specified otherwise, a field can be public, static, not static and final.
An attribute is another term for a field. It’s typically a public field that can be accessed directly.
In NetBeans or Eclipse, when we type object of a class and after that dot(.) they give some suggestion which are called Attributes.
A property is a term used for fields, but it typically has getter and setter combination.
Variables are comprised of fields and non-fields.
Fields can be either:
Static fields or
non-static fields also called instantiations e.g. x = F()
Non-fields can be either:
local variables, the analog of fields but inside a methods rather than outside all of them, or
parameters e.g. y in x = f(y)
In conclusion, the key distinction between variables is whether they are fields or non-fields, meaning whether they are inside a methods or outside all methods.
Basic Example (excuse me for my syntax, I am just a beginner)
Class {
//fields
method1 {
//non-fields
}
}
Actually these two terms are often used to represent same thing, but there are some exceptional situations. A field can store the state of an object. Also all fields are variables. So it is clear that there can be variables which are not fields. So looking into the 4 type of variables (class variable, instance variable, local variable and parameter variable) we can see that class variables and instance variables can affect the state of an object. In other words if a class or instance variable changes,the state of object changes. So we can say that class variables and instance variables are fields while local variables and parameter variables are not.
If you want to understand more deeply, you can head over to the source below:-
http://sajupauledayan.com/java/fields-vs-variables-in-java
Java variable, field, property
variable - named storage address. Every variable has a type which defines a memory size, attributes and behaviours. There are for types of Java variables: class variable, instance variable, local variable, method parameter
//pattern
<Java_type> <name> ;
//for example
int myInt;
String myString;
CustomClass myCustomClass;
field - member variable or data member. It is a variable inside a class(class variable or instance variable)
attribute - in some articles you can find that attribute it is an object representation of class variable. Object operates by attributes which define a set of characteristics.
CustomClass myCustomClass = new CustomClass();
myCustomClass.myAttribute = "poor fantasy"; //`myAttribute` is an attribute of `myCustomClass` object with a "poor fantasy" value
[Objective-C attributes]
property - field + bounded getter/setter. It has a field syntax but uses methods under the hood. Java does not support it in pure form. Take a look at Objective-C, Swift, Kotlin
For example Kotlin sample:
//field - Backing Field
class Person {
var name: String = "default name"
get() = field
set(value) { field = value }
}
//using
val person = Person()
person.name = "Alex" // setter is used
println(person.name) // getter is used
[Swift variable, property...]
The question is old but another important difference between a variable and a field is that a field gets a default value when it's declared.A variable, on the other hand, must be initialized.
My understanding is as below, and I am not saying that this is 100% correct, I might as well be mistaken..
A variable is something that you declare, which can by default change and have different values, but that can also be explicitly said to be final. In Java that would be:
public class Variables {
List<Object> listVariable; // declared but not assigned
final int aFinalVariableExample = 5; // declared, assigned and said to be final!
Integer foo(List<Object> someOtherObjectListVariable) {
// declare..
Object iAmAlsoAVariable;
// assign a value..
iAmAlsoAVariable = 5;
// change its value..
iAmAlsoAVariable = 8;
someOtherObjectListVariable.add(iAmAlsoAVariable);
return new Integer();
}
}
So basically, a variable is anything that is declared and can hold values. Method foo above returns a variable for example.. It returns a variable of type Integer which holds the memory address of the new Integer(); Everything else you see above are also variables, listVariable, aFinalVariableExample and explained here:
A field is a variable where scope is more clear (or concrete). The variable returning from method foo 's scope is not clear in the example above, so I would not call it a field. On the other hand, iAmAlsoVariable is a "local" field, limited by the scope of the method foo, and listVariable is an "instance" field where the scope of the field (variable) is limited by the objects scope.
A property is a field that can be accessed / mutated. Any field that exposes a getter / setter is a property.
I do not know about attribute and I would also like to repeat that this is my understanding of what variables, fields and properties are.
I am just refreshing the oops features of the java. So, I have a little confusion regarding inheritance concept. For that I have a following sample code :
class Super{
int index = 5;
public void printVal(){
System.out.println("Super");
}
}
class Sub extends Super{
int index = 2;
public void printVal(){
System.out.println("Sub");
}
}
public class Runner {
public static void main(String args[]){
Super sup = new Sub();
System.out.println(sup.index+",");
sup.printVal();
}
}
Now above code is giving me output as : 5,Sub.
Here, we are overriding printVal() method, so that is understandable that it is accessing child class method only.
But I could not understand why it's accessing the value of x from Super class...
Thanks in advance....
This is called instance variable hiding - link. Basically you have two separate variables and since the type of the reference is Super it will use the index variable from Super.
Objects have types, and variables have types. Because you put:
Super sup = new Sub();
Now you have a variable sup of type Super which refers to an object of type Sub.
When you call a method on an object, the method that runs is chosen based on the type of the object, which is why it prints "Sub" instead of "Super".
When you access a field in an object, the field is chosen based on the type of the variable, which is why you get 5.
index is simply a field belonging to the parent class. Because it belongs to the parent class, it means that it's an attribute to all the children.
To simply the concept:
A Class Animal could have a field age and a field name
All sub classes would share those attributes, but would have additional field(s), which would be contained into those children classes only. For example hairColour could be the only attribute of the Dog class, but not to the class Snake, which could have a simple unique attribute venomous
In this structure all Animal have a name, and an age, which is what could define Animals in general, an each specie have some extra attribute(s) unique to them, which are contained into their respective sub classes.
Your code doesn't clearly show this, as your sub class has no constructor, indeed no super constructor call. As explained by Petar, your none private attribute index is access from the super class
This happens coz functions follows runtime binding whereas variables are bound at compile time.
So the variables depend on the reference's datatype whereas the functions depend on the value represent by the reference's datatype.
When we assigning the object of sub class to parent class object only the common property both class can be accepted by the parent class object , is called as object slicing
that's why the value of patent class 5 is printed its only happen with property not a method