EXC - Class, Array of Class
EXC - Class, Array of Class
Classes,
Arrays of Classes
Exercise
Classes and Objects
• Јаva is an ОО language
• Java perceives the world as a collection of mutually
interacting objects
• A class is a general definition of characteristics (attributes)
and actions (methods) which are common for certain objects
from the “real world”
• The objects are instances (individuals) of classes
A Car class
Object Citroen_C5 of the class Car
The new operator
The operator for creating a class instance
Constructors
Ex.
Example:
Car my_car= new Car (“Citroen C5”,5, ”Gasoline”, ”Metallic grey”);
System.out.println(my_car.getName());
What is
getName()?
4
Compiling a JAVA file with
more than one class
1. There must be ONLY ONE public class in one file
2. JAVA file has same name as the public class.
3. public static void main (…) is part of the public class body.
4. Compiling is done with the name of the file i.e. name of the public class
Ex. javac main_class.java
5. After compiling, javac creates .class files for every defined class.
Imagine having N
vehicles, i.e. your
own drive park J.
Arrays of objects of the SAME
class
ArrayVehicles.java
int no_cars=5;
//creating an array of 5 objects of the Car class
Car[] DrivePark= new Car[no_cars];
//initialization of the array elements
DrivePark[0]=new Car("honda crv5", 7, "Diesel", "Cream");
DrivePark[1]=new Car();
DrivePark[2]=new Car("Audi A1",5,"gasoline","white");
DrivePark[3]=new Car();
DrivePark[4]=new Car();
//method invocation for an appropriate array element
DrivePark[3].setFuel("Diesel");
System.out.println(DrivePark[0].getType());
DrivePark[2].spec();