[Go to site: main page, start]

0% found this document useful (0 votes)
7 views9 pages

Java Classes and Objects Overview

This document covers the basics of classes and objects in Java, including the concepts of classes as blueprints, objects as instances, and access modifiers such as public and private. It explains the use of the final keyword, static methods and variables, constructors, and the importance of packages and imports. Additionally, it discusses memory management, object references, variable reassignment, local variables, and garbage collection in Java.

Uploaded by

manojna9d
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views9 pages

Java Classes and Objects Overview

This document covers the basics of classes and objects in Java, including the concepts of classes as blueprints, objects as instances, and access modifiers such as public and private. It explains the use of the final keyword, static methods and variables, constructors, and the importance of packages and imports. Additionally, it discusses memory management, object references, variable reassignment, local variables, and garbage collection in Java.

Uploaded by

manojna9d
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Week 2: Basics of Classes and Objects

(Java) - Notes
1. Classes and Objects
- Class = blueprint (like a recipe).
- Object = instance created from a class (like an actual cake from the recipe).
Example:
class Dog { }
Dog d1 = new Dog(); // object created

- You can have arrays of objects just like arrays of numbers.


- Good practice: keep the main() method in a different class from the one being tested.

2. Access Modifiers: Public and Private(More about this in week 3 doc)


- public class → must live in its own file with the same name.
Example:
public class Dog { }
→ must be in [Link]

- Toy box analogy:


Imagine you have toys (classes). Each toy has its own name. Public toys must have their
own toy box with the same name as the toy. For example, if you have a toy called Car, you
must keep it in a box called [Link].

- private keyword → hides data from outside classes. Cannot use it outside that file.
- Use getters and setters to access/update private fields.
Example:
class Student {
private String name;
public String getName() { return name; }
public void setName(String n) { name = n; }
}

- Analogy: private is like a locked room in your house; only the house owner can access it.

3. Final Keyword
- final variable = WORM (Write Once, Read Many).
- Once initialized, value cannot be reassigned.
- Can be applied to primitive values or object references.
Example:
final int MAX = 100;

4. Static Methods and Variables


GO THROUGH STATICLEC CODE.

- static = belongs to the class, not an individual object.


- Static variable → single shared copy across all objects.
- Static method → can be called without creating an object.
- Example: [Link](4).

- Analogy:
• Students have individual lunchboxes (normal variables).
• The classroom has one big shared chocolate jar (static variable).
• A static method is like asking the teacher directly, not a student.

Code Example:
class Student {
String name;
static int chocolateJar = 10;

Student(String n) { name = n; }

void eatChocolate() {
chocolateJar--;
[Link](name + " ate one. Left: " + chocolateJar);
}

static void refill(int amount) {


chocolateJar += amount;
}
}

5. Constructors and Overloading


So when we do Box box3= new Box(), java looks if there is a constructor Box(), usually there
exists a default constructor
But let’s say we do Box box3= new Box(1,2,3), then java looks for a constructor in our Box
class which accepts 3 arguments.

- A constructor is called when you create an object.


- Implicit constructor: provided automatically if none defined.
- Explicit constructor: same name as class, no return type.
- Overloading: multiple constructors with different parameters.

6. Initialization
- Ways to initialize:
1. In the constructor.
2. At declaration: int x = 10;
3. Initialization blocks { }.
- Must always initialize before reading a variable.

7. Packages and Imports


Let’s say I have a class “[Link]”, if I want to create another class of same name
“[Link]”, then I won’t be able to do it.

So here Packages come and help us.

You can create one “[Link]” in one folder and another “[Link]” in another folder.

Packages are containers for classes, boxes which hold classes.

It is just a folder.

When writing a code, you have to mention which package it lies in.

Now to use the files/methods of package “A” in package “B”, then we just have to import
package “A” in “B”.

Two types of Packages-

1) User-defined
2) In-built packages
 lang
 io
 util
 applet
 awt
 net

- Access a class by full name ([Link]) or by import.


Example:
import [Link].*;
LocalDate today = [Link]();
8. Memory Basics
- Memory stores references to objects.
Example:
PetShop p = new PetShop(); → p stores the address of the PetShop object.
- Variables are like name tags pointing to real objects in memory.

9. Objects as Parameters (Under the Hood)


The Code Example from Slides

public class PetShop {


public PetShop() {
[Link]();
}

public void testGroomer() {


Dog django = new Dog();
DogGroomer groomer = new DogGroomer();
[Link](django);
}
}

public class DogGroomer {


public DogGroomer() {
// this is the constructor!
}

public void groom(Dog shaggyDog) {


// code that grooms shaggyDog goes here!
}
}

Step 1: Object Creation in Memory

When the program runs:

1. Dog django = new Dog();


→ Java creates a Dog object in memory. The variable django is a reference pointing
to that Dog.
Think of django as a name tag pointing to a real dog in the park.

2. DogGroomer groomer = new DogGroomer();


→ Java creates a DogGroomer object in memory. The variable groomer points to it.

Important: The variables (django, groomer) don’t store the objects directly — they store
addresses (references) to where those objects live in memory.
Step 2: Passing an Object as a Parameter

[Link](django);

 Here, we call the groom method.

 The method expects a Dog parameter, called shaggyDog.

What gets passed?

 Not the dog itself, but the reference (address) of django.

 Inside the method, shaggyDog is another name tag pointing to the same Dog object
in memory.

So now both:

 django (outside method)

 shaggyDog (inside method)

are pointing to the same Dog.

Step 3: Inside the Method

public void groom(Dog shaggyDog) {

// code that grooms shaggyDog goes here!

 The groom method doesn’t get a copy of the dog.

 Instead, it gets another reference to the same Dog.

 That means if the groomer changes the dog (e.g., [Link]()), the changes
are visible outside too, because django and shaggyDog both point to the same
memory.

Summary-
Step 1: Create Dog and DogGroomer objects in memory.
Step 2: Variables (django, groomer) hold references (addresses).
Step 3: [Link](django) passes the reference into the method.
Inside groom(Dog shaggyDog), shaggyDog points to the same Dog as django.
Key Point: Java passes object references by value. The reference itself is copied, not the
object.

Objects live somewhere in memory.

Variables store references to these objects, not the actual objects.

When you pass an object to a method, Java passes the reference by value.

 That means the method parameter points to the same object, but the reference
variable itself is copied.

Any changes to the object inside the method affect the same object outside.

Analogy: Imagine a dog named Django is in a park. You have a map with Django’s location
(django). You give a copy of the map to the groomer (shaggyDog). Both maps point to the
same real Django. If the groomer cuts Django’s hair, you’ll see Django is trimmed too.

10. Variable Reassignment (Under the Hood)


Code Example:
Dog django = new Dog();
[Link](django);
django = new Dog(); // reassignment
[Link](django);

Step 1: Create the first Dog. django points to Dog #1.


Step 2: Groom Dog #1.
Step 3: Reassign django = new Dog(); Now django points to Dog #2.
Step 4: Dog #1 has no references → eligible for garbage collection.
Step 5: Groomer now works on Dog #2.

Analogy: You adopt a puppy named Django and tie a tag 'django' on him. You take him to the
groomer. Later, you adopt a new puppy and put the 'django' tag on this one. Now the
groomer grooms the new dog. The old puppy still exists, but without a name tag, he’s
forgotten (garbage collected).

11. Local Variables


- Variables declared inside methods.
- Scope = only within that method.
- After method ends, they disappear.
- Example:
void test() {
Dog d = new Dog(); // local variable
}
// after method ends, d is gone
- Any objects no longer referenced → garbage collected.

12. Garbage Collection


- Java automatically frees memory of objects that are no longer referenced.
- Example:
Dog django = new Dog();
django = new Dog(); // old Dog is now unreachable
- Old object becomes eligible for garbage collection.

GO THROUGH THE LEC2 CODE.

Let’s say we have two classes we can create an object using both of them as follows-

Engine car= new Car();

What things to access depends on Engine and which version of that to access depends on
Car()
Engine has acc(), start(), stop(). Car() has acc(), start(), stop(), brake(). But “car” will only
access acc(), start(), stop() from Car(), because only these are defined in Engine(). We will
not be able to access brake().

You might also like