Java 2
Java 2
Java 2
Date: / /
Practical No.2
Practical No.2
Title:Write a Java Program to define a class, overload the constructors and instantiate its
object.
Class: Class is a collection of objects of similar type. Once a class has been defined, we can
create any number of objects belonging to that class. It is a logical entity. Example: Fruit;
In Java everything is encapsulated under classes. Class is the core of Java language. Class can
be defined as a template/ blueprint that describe the behaviors /states of a particular entity. A
class defines new data type. Once defined this new type can be used to create object of that
type. A class is declared using class keyword. A class contain both data and code that operate
on that data. A class is a group of objects that has common properties. A class in java can
contain: data member, method, constructor, block, class and interface.
Syntax:
class
Data members;
Member method;
Main method;
It must have the class keyword, and class must be followed by a legal identifier.
It may optionally extend one parent class. By default, it will extend java.lang.Object.
The class's variables and methods are declared within a set of curly braces {}.
Each .java source file may contain only one public class. A source file may contain any
number of default visible classes.
Finally, the source file name must match the public class name and it must have a .java
suffix.
Constructors
A constructor is a special method that is used to initialize an object. Every class has a
constructor, if we don't explicitly declare a constructor for any java class the compiler builds
a default constructor for that class. A constructor does not have any return type. A constructor
has same name as the class in which it resides. Constructor in Java cannot be abstract, static,
final or synchronized. These modifiers are not allowed for constructor. Java constructor is
invoked at the time of object creation. It constructs the values i.e. provides data for the object
that is why it is known as constructor.
1. Default Constructor
<class name> ()
{ //initialization
Example:
class Bike1
Bike1()
System.out.println("Bike is created");
}}
Parameterized Constructor
Example:
class Student4
int id;
String name;
Student4(int i,String n)
id = i;
name = n;
void display()
System.out.println(id+" "+name);
s1.display(); s2.display();
Constructor Overloading
you have multiple methods with same name but different signature, whereas in Constructor
overloading you have multiple constructor with different signature but only difference is that
Constructor doesn't have return type in Java. Constructor overloading is done to construct
object in different ways.
Example:
class Student5
int id;
String name;
int age;
Student5(int i,String n)
id = i; name = n;
id = i; name = n; age=a;
void display()
s1.display();
s2.display();
Program 1:
Out put: