Object Oriented Programming in Java
Module 2 - Programming Assignment Instructions
Objects, memory models, and scope
1.
Consider the following code:
What would this code print?
Note that this might seem like a compiler error to be accessing c1.a and c1.b from main, but because the method main is defined in the class "MyClass", it will compile just fine (feel free to check it for yourself).
Although "a" is a private variable, because the method "main" is in the class MyClass, it has access to that private variable. So this will run just as you'd expect.
2.
What is the result of running the code above? Hint - draw a memory model!
Yes, both c1 and c2 refer to the same object. So when you change c1.a, you have effectively changed c2.a as well.
3.
In the code from question 2 above, after executing c2 = c1, how can you get back the object which c2 previously pointed to (the one with a as 10 and b as 31.5)?
Without any references pointing to that object originally referred to by c2, the garbage collector can destroy the object. If you needed to keep that object around for later, you'd need to assign it to a temporary reference.
4.
Please review the code below:
Please review the code below:
What would be the output from running main?
This is the correct response. c2's values are incremented by passing it as a parameter to incrementBoth.
5.
Please review the code below:
Please review the code below:
What is the output from running this code?
This is the correct response. This is a tricky question, because methods incrementA and incrementB have no real purpose. Because Java is pass by value, a copy of that value is passed into the method. Changing the copy of the primitive type will have no impact on the parameter.
0 Comments
If you have any doubts/suggestion/any query or want to improve this article, you can comment down below and let me know. Will reply to you soon.