CJP Unit-4
CJP Unit-4
Unit-04
Objects and Classes
Class
Object
Class
Class is derived datatype, it combines members of different datatypes into one.
Defines new datatype (primitive ones are not enough).
For Example : Car, College, Bus etc..
This new datatype can be used to create objects.
A class is a template for an object .
Example :
class Car{
String company;
String model;
double price;
double milage;
………
}
Class: Car
Properties (Describe)
Company
Model Methods (Functions)
Color Start
Mfg. Year Drive
Price Park
Fuel Type On_break
Mileage On_lock
Gear Type On_turn
Power Steering
Anti-Lock braking system
Prof. Arjun V. Bala #3140705 (OOP-I) Unit 04 – Object and Class 4
Object
An object is an instance of a class.
An object has a state and behavior.
Example: A dog has
states - color, name, breed as well as
behaviors – wagging the tail, barking, eating.
The state of an object is stored in fields (variables), while methods (functions) display the
object's behavior.
length = 3
length = 5 length = 5
width = 3
width = 2 width = 2
borderColor=red
borderColor=black borderColor=none
backgroundColor=
backgroundColor=white length = 2 backgroundColor=yellow
white
width = 5
borderColor=black
backgroundColor=
white
Properties of constructor:
Constructor is invoked automatically whenever an object of class is created.
Constructor name must be same as class name.
Constructors do not have return types and they cannot return values, not even void.
All classes have constructors by default: if you do not create a class constructor yourself, Java
creates one for you. However, then you are not able to set initial values for object attributes.
Types of Constructor
1. Default Constructor
2. Parameterized Constructor
college DIET
Prof. Arjun V. Bala #3140705 (OOP-I) Unit 04 – Object and Class 21
static method
If you apply static keyword with any method, it is known as static method.
A static method belongs to the class rather than the object of a class.
A static method can be invoked without the need for creating an instance of a class.
A static method can access static data member and can change the value of it.
Restrictions
1. The static method can not use non static data member or call non-static method directly.
2. this and super cannot be used in static context.
class Student {
// code
}
The package statement should be the first line in the source file.
There can be only one package statement in each source file, and it applies to all types in the file.
If a package statement is not used then the class/interfaces will be put into an unnamed
package.