![]() |
![]() |
Java Interface | |
Java Class vs Interface | |
Java Multiple Inheritance | |
Java Nested Interface |
Java Packages | |
Java Built in packages | |
Java Package Access Specifiers |
Java Programs | |
Java Keywords Dictionary | |
Java Interview Questions |
Class is a user defined data type.
All the data/fields and methods/functions are encapsulated within the class. The data and methods written within the class are called as members of class.
When we define any class, we are not defining any data, we just define a structure or a blueprint, as to what the object of that class type will contain and what operations can be performed on that object.
Syntax
class className { // instance variable declaration type/datatype variable1; type/datatype variable2; . . . type/datatype variableN; // method declaration return_type method_name( parameter list..) { // body of method } }
Instance variable declaration
they are called as instance variables because they are created whenever an object of the class is instantiated. These are accessible to all the functions written inside the class.
Method declaration
Method means functions. Methods are used for working on the data contained in the class.
Consider the Class of Cars. There may be many cars with different names and brand but all of them will share some common properties like all of them will have 4 wheels, Speed Limit, Mileage etc. So here, Car is the class and wheels, speed limits, mileage are their properties.
class Cars { static byte wheels; static int speed_limit, mileage; static void apply_break() { System.out.println("Break pressed"); } static void increase_speed() { System.out.println("Speed increased"); } public static void main(String args[]) { wheels = 4; speed_limit = 120; mileage = 23; System.out.println("wheels : "+wheels+" speed limit : " +speed_limit+" mileage : "+mileage); apply_break(); // calling member function increase_speed(); } }
Output
In the above example of class Cars, the data member will be speed limit, mileage etc. and member functions can be applying brakes, increase speed etc.
In java, the main method accepts only static type of data and methods from outside the main method. that’s why we have not to worry about creating an object of same class for calling the methods or initializing the fields.
We will Learn more about static keyword on later tutorial.