Object and Classes,Java is an Object-Oriented Language. As a language that has the Object-Oriented function, Java supports the following fundamental concepts −
- Polymorphism
- Inheritance
- Encapsulation
- Abstraction
- Classes
- Objects
- Instance
- Method
- Message Passing
In this chapter, we are able to look at the standards – Classes and Objects.
- Object − Objects have states and behaviors. Example: A dog has states – colour, name, breed in addition to behaviors – wagging the tail, barking, ingesting. An item is an instance of a class.
- Class − A class may be defined as a template/blueprint that describes the conduct/nation that the item of its type help.
Object and Classes,Objects in Java
Object and Classes,Let us now appearance deep into what are gadgets. If we don’t forget the actual-world, we can find many gadgets around us, automobiles, dogs, human beings, etc. All those items have a state and a conduct.
If we take into account a dog, then its country is – call, breed, coloration, and the conduct is – barking, wagging the tail, going for walks.
If you evaluate the software object with a real-international object, they have very comparable characteristics.
Software objects actually have a country and a behavior. A software program item’s country is stored in fields and conduct is shown through techniques.
So in software development, strategies operate on the internal kingdom of an object and the item-to-object communication is finished through strategies.
Object and Classes,Classes in Java
A class is a blueprint from which individual objects are created.
Following is a sample of a class.
Example
public class Dog {
String breed;
int age;
String color;
void barking() {
}
void hungry() {
}
void sleeping() {
}
}
A elegance can include any of the following variable sorts.
- Local variables − Variables defined internal strategies, constructors or blocks are referred to as local variables. The variable will be declared and initialized inside the method and the variable will be destroyed whilst the approach has completed.
- Instance variables − Instance variables are variables inside a category however outside any method. These variables are initialized while the elegance is instantiated. Instance variables may be accessed from internal any method, constructor or blocks of that specific magnificence.
- Class variables − Class variables are variables declared within a category, outdoor any approach, with the static key-word.
A magnificence could have any quantity of strategies to get admission to the price of various kinds of methods. In the above instance, barking(), hungry() and sleeping() are techniques.
Following are some of the critical subjects that need to be discussed while looking into training of the Java Language.
Object and Classes,Constructors
Object and Classes,When discussing about training, one of the most important sub subject matter would be constructors. Every class has a constructor. If we do now not explicitly write a constructor for a category, the Java compiler builds a default constructor for that magnificence.
Each time a brand new item is created, as a minimum one constructor might be invoked. The main rule of constructors is they ought to have the same call as the class. A class can have a couple of constructor.
Following is an instance of a constructor −
Example
public class Puppy {
public Puppy() {
}
public Puppy(String name) {
// This constructor has one parameter, name.
}
}
Java also supports Singleton Classes where you’ll be capable of create most effective one example of a category.
Note: We have one of a kind styles of constructors. We are going to talk about constructors in detail in the next chapters.
Object and Classes,Creating an Object
As referred to previously, a category gives the blueprints for objects. So essentially, an item is produced from a class. In Java, the new keyword is used to create new items.
There are three steps whilst growing an item from a class −
- Declaration − A variable assertion with a variable call with an item kind.
- Instantiation − The ‘new’ keyword is used to create the object.
- Initialization − The ‘new’ key-word is accompanied via a call to a constructor. This call initializes the new item.
Following is an instance of creating an item −
Example
public class Puppy {
public Puppy(String name) {
// This constructor has one parameter, name.
System.out.println("Passed Name is :" + name );
}
public static void main(String []args) {
// Following statement would create an object myPuppy
Puppy myPuppy = new Puppy( "tommy" );
}
}
If we compile and run the above program, then it will produce the following result −
Output
Passed Name is :tommy
Object and Classes,Accessing Instance Variables and Methods
Object and Classes,Instance variables and strategies are accessed through created items. To get right of entry to an instance variable, following is the completely certified direction −
/* First create an object */
ObjectReference = new Constructor();
/* Now call a variable as follows */
ObjectReference.variableName;
/* Now you can call a class method as follows */
ObjectReference.MethodName();
Example
This example explains how to access instance variables and methods of a class.
public class Puppy {
int puppyAge;
public Puppy(String name) {
// This constructor has one parameter, name.
System.out.println("Name chosen is :" + name );
}
public void setAge( int age ) {
puppyAge = age;
}
public int getAge( ) {
System.out.println("Puppy's age is :" + puppyAge );
return puppyAge;
}
public static void main(String []args) {
/* Object creation */
Puppy myPuppy = new Puppy( "tommy" );
/* Call class method to set puppy's age */
myPuppy.setAge( 2 );
/* Call another class method to get puppy's age */
myPuppy.getAge( );
/* You can access instance variable as follows as well */
System.out.println("Variable Value :" + myPuppy.puppyAge );
}
}
If we compile and run the above program, then it will produce the following result −
Output
Name chosen is :tommy
Puppy's age is :2
Variable Value :2
Object and Classes,Source File Declaration Rules
Object and Classes,As the closing part of this phase, let’s now inspect the source document announcement guidelines. These regulations are important whilst asserting classes, import statements and package statements in a supply document.
- There may be most effective one public elegance in step with supply report.
- A source file could have multiple personal lessons.
- The public magnificence call need to be the name of the source file as nicely which have to be appended with the aid of .Java at the give up. For example: the class name is public magnificence Employee then the source file must be as Employee.Java.
- the class is defined interior a package, then the bundle assertion must be the first declaration in the supply file.
- import statements are gift, then they need to be written among the bundle statement and the magnificence assertion. If there are no bundle statements, then the import declaration should be the primary line within the supply report.
- Import and bundle statements will mean to all the instructions present within the source file. It isn’t feasible to declare exceptional import and/or package deal statements to distinct lessons within the source document.
Classes have numerous get admission to ranges and there are distinct forms of classes; summary instructions, very last instructions, and so forth. We might be explaining about some of these inside the get right of entry to modifiers chapter.
Apart from the above noted sorts of lessons, Java also has some unique lessons called Inner training and Anonymous classes.
Java Package
In simple words, it is a manner of categorizing the instructions and interfaces. When developing applications in Java, masses of instructions and interfaces might be written, consequently categorizing these lessons is a have to in addition to makes life an awful lot less complicated.
Import Statements
In Java if a fully qualified call, which incorporates the package deal and the magnificence name is given, then the compiler can effortlessly locate the supply code or classes. Import declaration is a way of giving the proper area for the compiler to find that particular elegance.
For instance, the following line would ask the compiler to load all the instructions to be had in listing java_installation/java/io −
import java.io.*;
A Simple Case Study
For our case have a look at, we are able to be creating training. They are Employee and EmployeeTest.
First open notepad and add the subsequent code. Remember this is the Employee class and the class is a public elegance. Now, keep this supply record with the name Employee.Java.
The Employee magnificence has 4 example variables – name, age, designation and earnings. The elegance has one explicitly described constructor, which takes a parameter.
Example
import java.io.*;
public class Employee {
String name;
int age;
String designation;
double salary;
// This is the constructor of the class Employee
public Employee(String name) {
this.name = name;
}
// Assign the age of the Employee to the variable age.
public void empAge(int empAge) {
age = empAge;
}
/* Assign the designation to the variable designation.*/
public void empDesignation(String empDesig) {
designation = empDesig;
}
/* Assign the salary to the variable salary.*/
public void empSalary(double empSalary) {
salary = empSalary;
}
/* Print the Employee details */
public void printEmployee() {
System.out.println("Name:"+ name );
System.out.println("Age:" + age );
System.out.println("Designation:" + designation );
System.out.println("Salary:" + salary);
}
}
As referred to previously on this tutorial, processing starts offevolved from the principle approach. Therefore, in order for us to run this Employee magnificence there must be a first-rate method and gadgets should be created. We may be developing a separate class for those duties.
Following is the EmployeeTest class, which creates times of the class Employee and invokes the methods for each item to assign values for every variable.
Save the subsequent code in EmployeeTest.Java record.
import java.io.*;
public class EmployeeTest {
public static void main(String args[]) {
/* Create two objects using constructor */
Employee empOne = new Employee("James Smith");
Employee empTwo = new Employee("Mary Anne");
// Invoking methods for each object created
empOne.empAge(26);
empOne.empDesignation("Senior Software Engineer");
empOne.empSalary(1000);
empOne.printEmployee();
empTwo.empAge(21);
empTwo.empDesignation("Software Engineer");
empTwo.empSalary(500);
empTwo.printEmployee();
}
}
Now, compile both the classes and then run EmployeeTest to see the result as follows −
Output
C:\> javac Employee.java
C:\> javac EmployeeTest.java
C:\> java EmployeeTest
Name:James Smith
Age:26
Designation:Senior Software Engineer
Salary:1000.0
Name:Mary Anne
Age:21
Designation:Software Engineer
Salary:500.0
What is Next?
In the subsequent consultation, we will speak the basic data kinds in Java and the way they can be used while developing Java programs.