Unit 2 Constructors
Unit 2 Constructors
Example
Class Bike1
{
Bike1()
{
System.out.println("Bike is created");
}
2. Parameterized Constructor :
-- A constructor with parameters.
-- If we want to initialize fields of the class with your own
values, then use parameterized constructor.
Class Student
{
String name;
Student(int i,String n)
{
id = i;
name = n;
}
void display()
{
System.out.println(id+""+name);}
public static void main(String args[])
{
Student s1 = new Student4(111,"Karan");
Student s2 = new Student4(222,"Aryan");
s1.display(); s2.display();
}
}
class Student
{
int rollno;
String name,course;
float fee;
System.out.println(rollno+""+name+""+co
urse+""+fee);
}
}
class Test
{
public static void main(String args[])
{
Student s1=new
Student(111,"ankit","java");
Student s2=new
Student(112,"sumit","java",6000);
s1.display();
s2.display();
}
}
super keyword in java
-- It is a reference variable which is
used to refer immediate parent class
object.
-- Whenever you create the instance of
subclass, an instance of parent class is
created implicitly which is referred by
super reference variable.
------------------------------------------------------------------------------------------------------
-----
Constant in Java
-- A constant is a variable which cannot
have its value changed after declaration.
It uses the 'final' keyword.
Syntax:
# Global constant
modifier final dataType variableName =
value;
------------------------------------------------------------------------------------------------------
---------
static fields(variables) of a class
------------------------------------------
----------------------------------------
class Student
{
static String college = "ITS";
void display ()
{
System.out.println(college);
}
O/P: SJCHS
Restrictions for static method
class A
{
int a=40; //non static
public static void main(String args[])
{
System.out.println(a);
}
}