How many objects are created in this case? [duplicate] - java

This question already has answers here:
String s = new String("xyz"). How many objects has been made after this line of code execute?
(21 answers)
Closed 5 years ago.
The title says it all
String a;
String b = new String("Hello");
I've seen a lot of questions like this but none of them had Strings that weren't initiated yet.
Can someone help me on this ?
Thank you.

You are creating a single object that is referenced by variable b, a is a declared variable without any data assigned to it, that is not an object in a Java sense

First row only declares a string variable, but doesn't create object. In the second row, a string object is created with a new keyword.
So there's only one object created.

Here is an explanation took from OCA Java SE 7 Programmer I Certification Guide: Prepare for the 1ZO-803 exam:
An object comes into the picture when you use the keyword operator new.
You can initialize a reference variable with this object. Note the difference between declaring a variable and initializing it. The following is an example of a class Person and another class ObjectLifeCycle:
class Person {}
class ObjectLifeCycle {
Person person;
}
In the previous code, no objects of class Person are created in the class ObjectLife-Cycle; it declares only a variable of type Person. An object is created when a reference variable is initialized:
class ObjectLifeCycle2 {
Person person = new Person();
}
Syntactically, an object comes into being by using the new operator. Because
Strings can also be initialized using the = operator, the following code is a valid example of String objects being created
class ObjectLifeCycle3 {
String obj1 = new String("eJava");
String obj2 = "Guru";
}

Related

Question about typecasting objects and accessing a method [duplicate]

This question already has answers here:
Casting variables in Java
(5 answers)
Why reference variable of type object must be cast when used as other object type
(4 answers)
Closed 3 years ago.
I'm a bit confused about the syntax of typecasting and the creation of objects. Here I have a code of
class OverridingTest{
public static void main(String [] args){
Dog dog = new Hound();
((Hound)dog).sniff();
}
}
class Dog{
public void bark(){
System.out.println("woof ");
}
}
class Hound extends Dog{
public void sniff(){
System.out.println("sniff ");
}
public void bark(){
System.out.println("bowl");
}
}
I do have some background about the syntax and casting. However, when I tried not casting the "dog" object it sends an error. I'm a bit confused on why the compiler does this.
I read some references about it and saw the syntax behind instantiating objects in the context of casting.
It said that in this line of code:
Dog dog = new Hound();
The "Dog" at the start of the line determines the "Type" of the objects. Specifically, it determines the operations the object can perform and the "Hound" which is the subclass of the "Dog" class,is the "Class" and determines the implementation of the methods that are available to the instantiated object.
Now that's the part where I started to get confused. Isn't it the way the "dog" object was instantiated is with reference to the "Hound" class already? Meaning the "dog" object has the implementation of the Hound class and therefore can access it's methods? Why would I need to add typecast operator when accessing its methods? Like this?
((Hound)dog).sniff();
Also, I have another question about it which is kind of a separate question but references of the same code. I tried instantiating the "dog" object with the class reference of the "Dog" class like this.
Dog dog = new Dog();
And then I put it into the subclass of a new line where
Hound newdog = (Hound) dog;
This follows the syntax of typecasting and compiles nicely. However, I get a run time error. Doesn't this follow the methods of casting? If not, how would I do it in another way?

I don't understand this common java principle [duplicate]

This question already has answers here:
How to instantiate an object in java?
(7 answers)
Closed 5 years ago.
Currently I'm following java course and I am struggling with a part of the code which I see used a lot in methods. So here goes:
Answer answer = new Answer("something");
I have a class named Answer and I think the first Answer is in reference to that. the lower cased answer is the variable. It's after the = sign I'm struggling to comprehend. any help please?
This declares a variable answer of type Answer and initializes it with a new object instance of class Answer by calling the Answer(String) constructor.
Consider Apollo's comment and google it.
This is not only a java principle but a generall programming principle.
You're creating a new Answer Object.
Let's look at this example:
public class Answer{ // The class
private String answer; // internal variable only visible for the class
public Answer(String answer){ // This is a constructor
this.answer = answer; // Here we assign the String we gave this object to an internal variable
}
public void setAnswer(String answer){ // Setter
this.answer = answer;
}
public String getAnswer(){ // Getter
return answer;
}
}
So now you have a class/Object named Answer.
When you now want to use it you need to create a new Object.
This is done over the constructor of a class. ( Constructor = basically a definition of what you need to create the Object )
First you declare what Object you want your variable to be, then you give the variable a name you can use it under.
That looks like this:
Answer variableName
But this will not create a new object.
To create it we need to give the keyword new in combination of a Constructor of the object we want to create.
As we defined a constructor that needs a String to create this object we need to call it like this:
new Answer("the string");
If we combine those two we finally have our usable new variable of a new create Answer
Answer yourVariable = new Answer("the string");
Any declaration in Java follows the following rules:
[variable type] [variable name] = [value];
So in your case:
variable type = object of type Answer
variable name = answer
value = new Answer("something")
What you're doing with new Answer("something") is that you're creating a new object of type Answer using the constructor that accepts a single String
Notice that the value is optional. You can just declare any value and assign a value after that
This is a pretty basic concept in Java.
Once we define a Java class, we can create objects of such class. To do so, we need to call a special method in the class, called constructor, with the reserved keyword new. Additionally, we want to store a reference to the newly created object in a variable, so that we can use it later.
To do so, we first declare a variable of the type of the class:
MyClass myVariable;
And then create an object and assign it to the variable:
myVariable = new MyClass();
In your case, the constructor receives one parameter of type String for initializing the object.

Finding an object by ID (Java) [duplicate]

This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 6 years ago.
I have a class Person, which have unique id of person (type int) for each Person object. I also have a static method isAlreadyStored(String name), which should check if a person with this name was already created. I can't solve this one by creating a list for all created Person objects, because I get error "non-static variable cannot be referenced from a static context", but I don't have any other idea how to iterate over all Person objects to find one with a given name. How do I approach this?
Apparently for solving your problem you need a list of all created instances for Person class. You should store that in a static variable, and then search on it. Something like this:
final static allPeople List<Person> = new ArrayList<Person>();
Then you could search on that list with something like this:
...
if (allPeople.contains(aPerson)){
...
The error non-static variable cannot be referenced from a static context means that you are trying to access a variable defined without the keyword static from a method defined with the keyword static.
For example
public class Main {
private int x = 3;
public static void main(String[] args) {
// Not possible
System.out.println(x);
}
}
A variable defined without the keyword static is named an instance variable and can be accessed only from an instance method (a method defined without the keyword static).

How to clone a object to a object of Object class?

As I have learned, Object class is a top level class and it is a parent of all classes. If we do not know a type of class at compile time, we can assign it to a object of Object class.
I am trying to clone a object to object of a Object class. Also trying to get the object from HashMap which is already instantiated. I am having problem in doing this. Can you figure out it and explain the right ways of doing it? I have commented in which lines I get compile time error. My main doubts are:
If a parent class' object can be used for cloning, then it must work with Object class too as it is top level class.
And how to access object from map and use it for method call and cloning.
Code:
import java.util.HashMap;
import java.util.Map;
class Sample {
public void call(){
}
}
class Question extends Sample implements Cloneable {
#Override
public void call(){
System.out.println("hello");
}
#Override
public Object clone()throws CloneNotSupportedException{
return super.clone();
}
public static void main(String args[]) throws CloneNotSupportedException{
Map<Character,Object> map=new HashMap();
Question s=new Question();
Sample q=new Question();
Sample cl=(Question)s.clone();
Object ob=(Question)s.clone();//no compile time error
map.put('o',s);
s.call();//hello
q.call();//hello
cl.call();/hello
ob.call();//Compile time error: cannot find symbol call
map.get('o').call();//Compile time error: cannot find symbol call
Object obj=(Question) (map.get('o')).clone();// Compile time error: clone has protected access in Object
}
}
The following line can be simplified
Object ob=(Question)s.clone();//no compile time error
// the cast is unnecessary:
Object ob= s.clone();
But like you said, the ob will still contain a Question object. The problem is that once you start using this ob reference, java just knows it contains a value of Object, or a subclass of it. So for java ob could be a Number or a String or an Airplane.
Object ob = "airplane";
Once it gets to the line ob.call() it refuses. Because it's not sure that the ob object has a call method. For example, if it was a String or a Number it would be impossible.
For this reason you have to perform a simple cast first:
((Question)ob).call();
// or
((Sample)ob).call();
Just let java know that it's an object with a call method.
The map#call issue has the same reasoning:
map.get('o').call();
//could be any of these
((Sample)map.get('o')).call();
((Question)map.get('o')).call();
But the last problem is more tricky. Actually a lot gets clear when you split up your statement in multiple lines:
Object obj=(Question) (map.get('o')).clone();
// would be the same like writing:
Object value = map.get('o');
Object value2 = value.clone();
Object obj = (Question) value2; // The (Question) cast is actually unnecessary.
The problem is in the value.clone() step. It is true that the Object class has a clone method, but it's marked as protected whereas the clone methods in your Question and Sample classes are public.
So in short Object#clone is not accessible ; Sample#clone and Question#clone are accessible.
// so you want this:
Object value = map.get('o');
Object value2 = ((Question)value).clone(); // add a cast here
Object obj = value2;
If you prefer to do it all in 1 line:
Object obj=((Question) (map.get('o'))).clone();

Why can I change private final ArrayList<Book>? [duplicate]

This question already has answers here:
Java final modifier
(2 answers)
Closed 9 years ago.
I have class that looks like this :
public class InformationSystem {
private final ArrayList<Book> books;
private final ArrayList<Reader> readers;
public InformationSystem() {
books = new ArrayList<Book>();
readers = new ArrayList<Reader>();
}
public void addBook(final String author, final String title) {
Book book = new Book(author, title);
books.add(book);
}
}
Why can I add/remove values from arraylist that is final?
I can't change the Car, Still I'm able to change the parts inside it :)
From Language specification # chapter 14.12.4
Once a final variable has been assigned, it always contains the same value. If a final variable holds a reference to an object, then the state of the object may be changed by operations on the object, but the variable will always refer to the same object.
You cannot re assign, still you can change the state.
In short
books =newBooksList; // huh! I'm final, No
books.add(book); //ok
What you want is to make your List immutable. See this post: java-immutable-collections
Or directly look at the java.util.Collections.unmodifiableList() method.
http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html?is-external=true#unmodifiableList%28java.util.List%29
Reference to an ArrayList object is final - you can't change that reference, you can't reassign.
But, you can call object's methods. In particular, even these methods, which change the state of the object.
So, ArrayList objects are mutable. On the other hand, for example, String objects are immutable. You can't change their internal state.
You have Created books object of type ArrayList as final.
so, books object refers ArrayList Object on the Heap, and as it is declared as final its reference will never change but you can change content of the object.
So, you can add/remove the items from ArrayList defined as final.
Keeping a Reference to an object final keeps the link pointing to the object as final, which cannot be changed. But the state of the actual object can change.
Link to which the reference variable points is final, the state of object to which it points is not final
If the object to which you are referring to is Immutable then you will achieve what you thought would happen.
final means that your reference is immutable - it cannot change.
However ArrayList is a mutable (can change) data structure.
You cannot change what books points to, but you can the data structure to which it points. In sum, you have an immutable reference to a mutable data structure.
Because you have declare the ArrayList variable book as a final variable so you can not reassign book with another object while you can do any thing with the current object.
ArrayList<Book> book = new ArrayList<Book>();
You can not reassign book variable like following.
ArrayList<Book> book2 = new ArrayList<Book>();
book = book2;
While you can do anything with the current book object because you are not changing the content of final variable you are changing content of object to which final variable is referencing.

Categories

Resources