Lect 6
Lect 6
Lecture 6
Classes and Object (part 1)
Classes provide
the structure
(mold) for
creating objects,
while objects are
the actual entities
that contain data
and behavior.
Objects Objects
Methods
• Note that when you create a class, you are creating a new type
in java that you can use to create instances of this type.
}
}
• Look next.
Enter name: c1
ma bmw
mo 3-series
y 2020
BMW Tesla
3-series Model S
2020 2022
C1 C2
Output
System.out.println(c1.model);
c1.model = "X6";
System.out.println(c1.model);
v
…
v
// variables and constructors not shown just for limited slide space.
Output
{
System.out.println("Make:” + make +", Model:” + model +", year:” + year);
Output
Can we do this?
Yes! Java understands
which is which.
Java knows exactly now that this.make is the class make variable, while make
(without this) is the parameter in the arguments list of the constructor.
All of them are seen as the parameters of the method, and hence our class
variables are left untouched. This means, that java will assign default
values for them, depending on their type. Look next.
Spring 2025 Dr. Milad Ghantous 30
Watch what happens
public Car(String make, String model, int year)
{
make = make;
model = model;
year = year;
Output
constructors
How to use them?
3
Output
• You can use it to create new Car objects, which of course, will
have default values.
}
public String toString(){
return "(" + x + "," + y + ")" ;
}
}
Spring 2025 Dr. Milad Ghantous 41
Tester
System.out.println(p1.toString());
Output
System.out.println(p2.toString());
}}