0% found this document useful (0 votes)
4 views29 pages

Lecture 2

The document provides an overview of Java programming concepts including classes, objects, constructors, method overloading, and the use of static keywords. It illustrates how to define classes and initialize objects through various methods, including reference variables, methods, and constructors. Additionally, it discusses the rules and types of constructors, as well as the significance of the 'this' keyword and static members in Java.

Uploaded by

aadityajoshi2k5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views29 pages

Lecture 2

The document provides an overview of Java programming concepts including classes, objects, constructors, method overloading, and the use of static keywords. It illustrates how to define classes and initialize objects through various methods, including reference variables, methods, and constructors. Additionally, it discusses the rules and types of constructors, as well as the significance of the 'this' keyword and static members in Java.

Uploaded by

aadityajoshi2k5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Web Technology

(KCS-602)
Lecture 2
Object and class example
//Java Program to illustrate how to define a class and fields
//Defining a Student class.
class Student{
//defining fields
int id;//field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[]){
//Creating an object or instance
Student s1=new Student();//creating an object of Student
//Printing values of the object
System.out.println(s1.id);//accessing member through reference variable
Output: 0
System.out.println(s1.name); null
}
}
main outside the class
//Java Program to demonstrate having the main method in
//another class
//Creating Student class.
class Student{
int id;
String name;
}
//Creating another class TestStudent1 which contains the main method
class TestStudent1{
public static void main(String args[]){
Student s1=new Student();
Output: 0
System.out.println(s1.id);
null
System.out.println(s1.name);
}
}
Ways to initialize object

 There are 3 ways to initialize object in Java.

1. By reference variable
2. By method
3. By constructor
By reference variable
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name=“Balagurusamy";
System.out.println(s1.id+" "+s1.name);//printing members with a white
space
} Output: 101 Balagurusamy
}
By method

class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n; }
void displayInformation(){System.out.println(rollno+" "+name); } }
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
Output: 111 Karan
s1.insertRecord(111,"Karan"); 222 Aryan
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation(); } }
Constructor

 a constructor is a block of codes similar to the method. It is called


when an instance of the class is created. At the time of calling
constructor, memory for the object is allocated in the memory.
 It is a special type of method which is used to initialize the object.
 Every time an object is created using the new() keyword, at least one
constructor is called.
Example of Constructor
Rules for creating Java constructor

There are some rules defined for the constructor.


 Constructor name must be the same as its class name.
 A Constructor must have no explicit return type.
 A Java constructor cannot be abstract, static, final, and synchronized.
 We can use access modifiers while declaring a constructor. It controls
the object creation. In other words, we can have private, protected,
public or default constructor in Java.
Types of Java constructors

 There are two types of constructors in Java:


1. Default constructor (no-arg constructor)
2. Parameterized constructor
Default Constructor

//Java Program to create and call a default constructor


class Bike1{
//creating a default constructor
Bike1(){
System.out.println("Bike is created");
}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
} Output: Bike is created
}
Parameterized Constructor
 A constructor which has a specific number of parameters is called a parameterized constructor.
//Java Program to demonstrate the use of the parameterized constructor.
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n; }
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display(); } }
Copy Constructor
class Rectangle
{
int length;
int breadth;
//constructor to initialize length and bredth of rectang of rectangle
Rectangle(int l, int b)
{
length = l;
breadth= b;
}
//copy constructor
Rectangle(Rectangle obj)
{
System.out.println("Copy Constructor Invoked");
length = obj.length;
breadth= obj.breadth;
}
//method to calcuate area of rectangle
int area()
{
return (length * breadth);
}}
//class to create Rectangle object and calculate area
class CopyConstructor {
public static void main(String[] args) {
Rectangle firstRect = new Rectangle(5,6);
Rectangle secondRect= new Rectangle(firstRect);
System.out.println("Area of First Rectangle : "+ firstRect.area());
System .out.println("Area of First Second Rectangle : "+ secondRect.area()); }}
Method Overloading
 Method Overloading is a feature that allows a class to have more than one method having the
same name, if their argument lists are different.
 If we have to perform only one operation, having same name of the methods increases the
readability of the program.
 Method overloading increases the readability of the program.
 Method overloading is an example of Static Polymorphism.
 Static Polymorphism is also known as compile time binding or early binding.
 Static binding happens at compile time. Method overloading is an example of static binding
where binding of method call to its definition happens at Compile time.
 Invalid case of method overloading: if two methods have same name, same parameters
and have different return type, then this is not a valid method overloading example. This will
throw compilation error.

 int add(int, int)


 float add(int, int)
Three ways to overload a method

 In order to overload a method, the argument lists of the methods must differ in
either of these:
1. Number of parameters.
For example: This is a valid case of overloading
add(int, int)
add(int, int, int)
2. Data type of parameters.
For example:add(int, int)
add(int, float)
3. Sequence of Data type of parameters.
For example:
add(int, float)
add(float, int)
Example 1: Overloading – Different Number of parameters in argument list

class DisplayOverloading
{ public void disp(char c)
{
System.out.println(c); }
public void disp(char c, int num) {
System.out.println(c + " "+num);
} }
class Sample
{ public static void main(String args[])
{ DisplayOverloading obj = new DisplayOverloading();
obj.disp('a');
obj.disp('a',10); Output:a
} }
a 10
Example 2: Overloading – Difference in data type of parameters

class DisplayOverloading2
{ public void disp(char c)
{ System.out.println(c); }
public void disp(int c)
{ System.out.println(c ); } }
class Sample2
{ public static void main(String args[])
{ DisplayOverloading2 obj = new DisplayOverloading2();
obj.disp('a');
obj.disp(5); } }

Output : a

5
Example3: Overloading – Sequence of data type of arguments

class DisplayOverloading3
{ public void disp(char c, int num)
{ System.out.println("I’m the first definition of method disp” +c);
}
public void disp(int num, char c)
{ System.out.println("I’m the second definition of method disp” + c );
} }
class Sample3
{ public static void main(String args[])
{
DisplayOverloading3 obj = new DisplayOverloading3();
obj.disp('x', 51 );
Output: I’m the first definition of method disp 51
obj.disp(52, 'y'); }} I’m the second definition of method disp 52
Constructor overloading

 Constructor overloading is a concept of having more than one


constructor with different parameters list, in such a way so that each
constructor performs a different task.
class Student {
int Roll;
String Name;
double Marks;
Student(int R,String N,double M) // Constructor 1 {
Roll = R;
Name = N;
Marks = M; }
Student(String N,double M,int R) // Constructor 2 {
Roll = R;
Name = N;
Marks = M; }
void Display() {
System.out.print("\n\t" + Roll+"\t" + Name+"\t" + Marks); } }
class ConstructorOverloadingDemo { Output: Roll Name Marks
public static void main(String[] args) {
1 Kumar 78.53
Student S1 = new Student(1,"Kumar",78.53); // Statement 2
2 Sumit 89.42
Student S2 = new Student("Sumit",89.42,2); // Statement 1
System.out.print("\n\tRoll\tName\tMarks\n");
S1.Display();
role of this () in constructor overloading

public class OverloadingExample2{


private int rollNum;
OverloadingExample2() {
rollNum =100; }
OverloadingExample2(int rnum) {
this();
/*this() is used for calling the default
* constructor from parameterized constructor.
* It should always be the first statement
* inside constructor body.
*/
rollNum = rollNum+ rnum; }
public int getRollNum() {
return rollNum; }
public void setRollNum(int rollNum) { Output: 112
this.rollNum = rollNum; }
public static void main(String args[]) {
OverloadingExample2 obj = new OverloadingExample2(12);
this keyword
 There can be a lot of usage of this keyword. In java, this is a reference variable that refers to the current
object.

Usage of java this keyword: Here is given the 6 usage of java this keyword.

 this can be used to refer current class instance variable.


 this can be used to invoke current class method (implicitly)
 this() can be used to invoke current class constructor.
 this can be passed as an argument in the method call.
 this can be passed as argument in the constructor call.
static keyword

 Static keyword can be used with class, variable, method and block. Static members belong
to the class instead of a specific instance, this means if you make a member static, you
can access it without object.
The static can be:
 Variable (also known as a class variable)
 Method (also known as a class method)
 Block
 Nested class
Java static variable
 If you declare any variable as static, it is known as a static variable.
 The static variable can be used to refer to the common property of all objects (which is not unique
for each object), for example, the company name of employees, college name of students, etc.
 The static variable gets memory only once in the class area at the time of class loading.
 Advantages of static variable: It makes your program memory efficient (i.e., it saves
memory).
Understanding the problem without static variable
class Student{
int rollno;
String name;
String college="ITS";
}
 Suppose there are 500 students in my college, now all instance data members will get memory
each time when the object is created. All students have its unique rollno and name, so instance
data member is good in such case. Here, "college" refers to the common property of all objects. If
we make it static, this field will get the memory only once.
 //Java Program to demonstrate the use of static variable
class Student{
int rollno;//instance variable
String name;
static String college =“ABESEC";//static variable
//constructor
Student(int r, String n){
rollno = r;
name = n; }
//method to display the values
void display (){System.out.println(rollno+" "+name+" "+college);} }
//Test class to show the values of objects
public class TestStaticVariable1{
public static void main(String args[]){ Output: 111 Karan ABESEC
222 Aryan ABESEC
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
//we can change the college of all objects by the single line of code
//Student.college=“ABES";
s1.display();
Java 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.
 Example of static method
//Java Program to get the cube of a given number using the static method
class Calculate{
static int cube(int x){
return x*x*x; }
public static void main(String args[]){
Output: 125
int result=Calculate.cube(5);
System.out.println(result); } }
Java static block

 Is used to initialize the static data member.


 It is executed before the main method at the time of classloading.
 Example:
class A2{
static{System.out.println("static block is invoked");}
public static void main(String args[]){
System.out.println("Hello main");
}
Output:static block is invoked
} Hello main
Static Class

 A class can be made static only if it is a nested class.


 Nested static class doesn’t need reference of Outer class
 A static class cannot access non-static members of the Outer class
class JavaExample{
private static String str = "BeginnersBook";
//Static class
static class MyNestedClass{
//non-static method
public void disp() {
/* If you make the str variable of outer class non-static then you will get compilation error
* because: a nested static class cannot access non-static members of the outer class.
*/
System.out.println(str); } }
public static void main(String args[]) {
/* To create instance of nested class we didn't need the outer class instance but for a regular
*nested class you would need to create an instance of outer class first */
JavaExample.MyNestedClass obj = new JavaExample.MyNestedClass();
Output: BeginnersBook
obj.disp(); } }

You might also like