CH_2 Classes and Objects
CH_2 Classes and Objects
EX1.
EX2.
Syntax of defining class:
class classname
{
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list)
{ // body of method }
type methodname2(parameter-list)
{ // body of method }
// ...
type methodnameN(parameter-list)
{ // body of method }
}
OBJECT:
In order to store the data for the data members of the class, we must create an object.
1. Instance of a class is known as an object. (instance is a mechanism of allocating sufficient
amount of memory space for data members of a class).
2. Class variable is known as an object.
3. Value form of a class is known as an object.
4. Logical runtime entity is known as an object.
5. Real world entities are called as objects.
6. An object is anything that really exists in the world and can be distinguished from others.
JAVA always follows dynamic memory allocation but not static memory allocation.
In order to create a memory space in JAVA we must use an operator called new. This new operator is
known as dynamic memory allocation operator.
Syntax:
o ClassName obj_name=new ClassName();
OR
o ClassName obj_name; // declare reference to object or Object declaration
o Obj_name=new Classname(); // allocate memory object or object referencing
When an object is declared it is set to a null value, since, there is no memory space.
When the object is referenced the value of the object memory space is created for the data members
of the class
The dot operator (.) or member selection operator is used to access the instance variables of the class.
Syntax: obj_name.variablename
EX:
class Box
{ double width;
double height;
double depth;
}
/* A program that uses the Box class. Call this file BoxDemo.java*/
class Box {
double width;
double height;
double depth;
}
// This class declares an object of type Box.
class BoxDemo {
public static void main(String args[])
{
Box mybox = new Box();
double vol;
Data Abstraction:
Data abstraction is the process of hiding certain details and showing only essential
information to the user.
OR
Data Abstraction is a mechanism of retrieving the essential details without dealing with
background details.
Data Encapsulation:
Binding (or wrapping) code and data together into a single unit are known as encapsulation.
OR
“Data encapsulation is the process wrapping data and associated methods in a single unit”.
Data encapsulation is basically used to achieve data/information hiding i.e. security.
EX. Write a class circle having methods to accept radius and to compute circumference and
area of circle.
Constructors
Constructor is a special type of method that is used to initialize the state of an object.
Constructor is invoked at the time of object creation.
It constructs the values i.e. data for the object that is why it is known as constructor.
Constructor is just like the instance method but it does not have any explicit return type.
Rules for creating constructor
There are basically two rules defined for the constructor.
1. Constructor name must be same as its class name
2. Constructor must have no explicit return type
3. Access modifier should be public
Types of constructors
There are two types of constructors:
default constructor (no-arg constructor)
parameterized constructor
1) Default Constructor
A constructor that have no parameter is known as default constructor.
Syntax of default constructor:
<class_name>(){…….}
2) Parameterized constructor
A constructor that have parameter is known as parameterized constructor.
Syntac:
<class_name>(argumentlist){…….}
Constructor Overloading
Constructor overloading is a technique in Java in which a class can have
any number of constructors that differ in parameter lists. The compiler
differentiates these constructors by taking into account the number of
parameters in the list and their type.
Example of Constructor Overloading
//Program of constructor overloading
class Student
{ int id; String name; int age;
Student()
{
id=0; name="Unknown"; age=0;
}
Student(int i,String n)
{ id = i; name = n; age=18; }
void display()
{ System.out.println(id+" "+name+" "+age);}
Array of Objects:
- Instead of creating object of particular class, we can create an array of objects.
- Syntax : ClassName[ ] arrayName = new ClassName[size];
- Syntax : ClassName arrayName[] = new ClassName[size];
-
EX: Write a program to accept student details (rno, name, percerntage) of N students and display it.(use
array of objects)
import java.util.Scanner;
class Student
{
int rollno;
String sname;
float per;
Student()
{ rollno=0; sname="Unknown"; per=0.0f; }
// OR Student(){}
void display()
{
System.out.println(rollno+"\t"+sname+"\t"+per);
}
}
class StudentDemo
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter no. of Student:");
int n=sc.nextInt();
Student sArr[]=new Student[n]; //
for(int i=0;i<n;i++)
{
System.out.print("Enter RollNo:");
int rno=sc.nextInt();
System.out.print("Enter Name:");
String sname=sc.next();
System.out.print("Enter percentage:");
float per=sc.nextFloat();
sArr[i]=new Student(rno,sname,per);
}
This Keyword:
this: ‘this’ is an internal or implicit object created by JAVA.
o ‘this’ object is internally pointing to current class object.
o Whenever the formal parameters and data members of the class are similar, to
differentiate the data members of the class from formal parameters, the data members
of class must be proceeded by ‘this’. (eg. this.var_name=….)
o this (): this () is used for calling current class default constructor from current class
parameterized constructors.
o this (…): this (…) is used for calling current class parameterized constructor from other
category constructors of the same class.
o Whenever we use either this () or this (…) in the current class constructors, that
statements must be used as first statement only.
Ex - Demonstration
public DemoStaticBlock()
{ System.out.println("Default Constructor"); }
obj1.display();
obj2.display();
//we can change the college of all objects by the single line of code
Student.college="Indira College";
obj1.display();
obj2.display();
}
}
EX2:
class Counter
{
static int count=0; //will get memory only once and retain its value
Counter()
{ count++; System.out.println(count); }
Static Methods:
o If we use static keyword with any method, it is known as static method.
o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a
class.
o A static method can access static data member and can change the value of it.
There are two main restrictions for the static method.
The static method cannot use non static data member or call non-
static method directly.
this and super cannot be used in static context.
o Math class static methods
public class Main {
public static void main( String[] args ) {
class ArithStaticDemo
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter two Numbers:");
int num1 = sc.nextInt();
int num2= sc.nextInt();
class TestObjectClass
{
public static void main(String [] args)
{
Test obj1=new Test(10,20);
Test obj2=new Test(10,20);
System.out.println("toString Method= "+ obj1.toString()) ;
System.out.println("getClass Method= "+ obj1.getClass()) ;
System.out.println("hasCode Method= "+ obj1.hashCode()) ;
System.out.println("equals Method= "+ obj1.equals(obj2));
Test obj3=obj1;
System.out.println("equals Method= "+ obj1.equals(obj3));
}
}
OutPut:
toString Method= Test@5acf9800
getClass Method= class Test
hasCode Method= 1523554304
equals Method= false
equals Method= true
String and StringBuffer Class:
- In Java, String and StringBuffer are classes used for handling text. Both serve the purpose
of manipulating character strings, but they have different characteristics and use cases. Here’s a
detailed comparison and explanation of String and StringBuffer:
- String Class
o Characteristics
Immutable: Once a String object is created, it cannot be changed. Any
modification to a string creates a new String object.
Common Methods
Length: int length()
Concatenation: String concat(String str)
Character Access: char charAt(int index)
Substring: String substring(int beginIndex, int endIndex)
Equality Check: boolean equals(Object obj), boolean
equalsIgnoreCase(String anotherString)
Comparison: int compareTo(String anotherString), int
compareToIgnoreCase(String anotherString)
Search: int indexOf(String str), boolean
contains(CharSequence s)
EX:
public class StringExample {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = str1.concat(" World"); // Creates a new String "Hello World"
formattedString = String.format("Name: %s, Age: %d, Score: %.2f", sname, age, score);
System.out.println(formattedString);
}
}
Output:
The number is 123
Pi to two decimal places: 3.14
Hello, Indira!
Name: AAA, Age: 23, Score: 95.12
Wrapper classes
- Wrapper classes in Java provide a way to use primitive data types as objects.
- They are part of the java.lang package and are used to convert primitive data types into
objects. This process is known as "boxing," and the reverse process (converting an object back
to a primitive type) is called "unboxing."
- Key Features of Wrapper Classes
o Immutability: Wrapper class objects are immutable, meaning their values cannot be
changed once they are created.
o Nullability: Unlike primitives, wrapper class objects can be null.
o Utility Methods: Wrapper classes provide several utility methods for converting
between different data types, parsing strings, etc. Wrapper classes provide utility
methods such as parseXxx, valueOf, toString etc.
o Constant Fields: Wrapper classes contain constant fields like MAX_VALUE and
MIN_VALUE to represent the maximum and minimum values of the primitive types.
- Eight primitive data types in Java and their corresponding wrapper classes:
Primitive Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
EX:
public class IntergerWrapperEx {
public static void main(String[] args) {
// Autoboxing: primitive to wrapper
int numPr1= 555; // this is primitive int
Integer numW1= numPr1; // Autoboxing
Packages
A package is a collection of related classes and interfaces. It provides a mechanism for
compartmentalizing classes. The Java API is organized as a collection of several predefined packages.
The java.lang package is the default package included in all java programs. The commonly used
packages are: java.lang, java.util, java.io, and java.net
Types of Packages
1. Built-in Packages: These are packages that come with the Java Development Kit (JDK). Examples
include java.lang, java.util, java.io, and java.net.
2. User-defined Packages: These are packages created by programmers to organize their own
classes and interfaces.
Creating a package:
- To create a user defined package, the package statement should be written in the source code
file.
- This statement should be written as the first line of the program. Save the program in a
directory of the same name as the package.
o Syntax : package packageName;
- Accessing a package: To access classes from a package, use the import statement.
o Syntax :
import packageName.*; //imports all classes
import packageName.className; //imports specified class
o Note that the package can have a hierarchy of sub-packages. In that case, the package
name should be qualified using its parent-packages while importing sub-packages.
There are two types of modifiers in Java: access modifiers and non-access modifiers.
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor,
or class. We can change the access level of fields, constructors, methods, and class by applying
the access modifier on it.
There are four types of Java access modifiers:
1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot
be accessed from outside the package. If you do not specify any access level, it will be
the default.
3. Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be
accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
Understanding Java Access Modifiers
Let's understand the access modifiers in Java by a simple table.
Access within class within package outside package by outside package
Modifier subclass only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
1. Private: The private access modifier is accessible only within the class.
Simple example of private access modifier
In this example, we have created two classes A and Simple. A class contains private data member and
private method. We are accessing these private members from outside the class, so there is a compile-time
error.
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
3. Protected:
- The protected access modifier is accessible within package and outside the package but
through inheritance only.
- The protected access modifier can be applied on the data member, method and
constructor. It can't be applied on the class.
- It provides more accessibility than the default modifer.
Example of protected access modifier
In this example, we have created the two packages pack and mypack. The A class of pack package is
public, so can be accessed from outside the package. But msg method of this package is declared as
protected, so it can be accessed from outside the class only through inheritance.
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output:Hello
4. Public:
- The public access modifier is accessible everywhere. It has the widest scope among all
other modifiers.
- Example of public access modifier
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello