5.2 Obj Behave
5.2 Obj Behave
Objects
By Upekha Vandebona
A Class
Class describes what an
object knows and what an
object does.
Song c2 = new Song();
c2.setArtist(“John Denver”);
c2.setTitle(“Country Roads”);
c2.play();
p3.play();
Size > Yes
“Woof!
60 Woof!”
No
No
“Yip! Yip!”
Exercise
Create an method to
depth
calculate and output
height the volume in the Box
Class
width
Void and Return
Methods can return values. Every
method should be declared with a
return type.
‘void’ return type means they don’t
give anything back.
If you declare a method to
void go(){ int go(){ return a value you must
return a value of the
return 34; declared type! (Or a value
that is compatible with the
} } declared type.)
Exercise
Create an method to
depth
calculate and return
height the volume in the Box
Class
width
Method Parameters and
Arguments
d.bark(3) ;
Create an method to
depth
set dimensions of the
height box, all at once.
width
Pass by Value 3
(pass~by~copy)
1
2
Method Signature
Method Name:
int add(int a, int b) {
Return Type: return a + b;
Parameter List: }
In this example:
Create an constructor
depth
to set dimensions of
height the box, all at once.
width
“this” Keyword
It is illegal in Java to declare two local variables with the same name
inside the same or enclosing scopes.
Interestingly, you can have local variables, including formal parameters
to methods, which overlap with the names of the class’ instance
variables. However, when a local variable has the same name as an
instance variable, the local variable hides the instance variable.
Garbage Collection
Garbage-Collectible Heap.
Each time an object is created in Java, it goes into
an area of memory known as The Heap.
All objects—no matter when, where, or how they’re
created—live on the heap.
But it’s not just any old memory heap; the Java
heap is actually called the Garbage-Collectible
Heap.
When you create an object, Java allocates memory
space on the heap according to how much that
particular object needs.
Java manages that memory
for you!
When the JVM can “see” that an object
can never be used again, that object
becomes eligible for garbage collection.
And if you’re running low on memory,
the Garbage Collector will run, throw out
the unreachable objects, and free up the
space so that the space can be reused.
Thank You!