Week 5
Week 5
5 / Lab 7
Class and Object, Defining Class, Instance Variables, Declaring Objects, Assigning Object Reference Variables,
Topics Covered Methods and Calling Methods, Constructor, The this Keyword, Math Class and its Methods
This is how you an create Students Object from class Student into Main class.
This command allocates memory for myCar To create an object in Java, declare it with
and initializes it based on the Car class.
Car myCar = new Car();
the class name and use the new keyword:
Declaring Objects
When you assign one object reference to Car car1 = new Car();
Assigning Object Reference Variables another, both references point to the same Car car2 = car1; // car2 now references the
object in memory. same object as car1
class Circle {
double radius; public returnType methodName(parameter
Methods define the actions that objects of a
list) {
class can perform. In a class, methods are
double calculateArea() { // Method body
usually named with verbs to represent
Methods
return Math.PI * radius * radius; }
actions.
}
}
class Person {
String name;
When you create an object with new, the // Constructor A constructor initializes new objects of a
constructor is called to initialize the object’s Person(String name) { Example of a Constructor: class. The constructor has the same name as Constructor
data. this.name = name; the class and no return type.
}
}
class Student {
String name;
Student(String name) {
The this Keyword Example:
this.name = name; // 'this.name' refers
to the instance variable
}
}
// Example usage
public class CalculatorDemo {
public static void main(String[] args) {
SimpleCalculator calculator = new SimpleCalculator(); // Create a new SimpleCalculator object