Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
11 views

Java Unit 1.3 (Classes)

The document discusses classes and objects in Java. It explains that classes are templates for objects and contain fields and methods. It provides examples of defining classes with fields and methods, creating objects of a class, and accessing object data and methods. It also covers constructors and the this keyword.

Uploaded by

Saranya
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Java Unit 1.3 (Classes)

The document discusses classes and objects in Java. It explains that classes are templates for objects and contain fields and methods. It provides examples of defining classes with fields and methods, creating objects of a class, and accessing object data and methods. It also covers constructors and the this keyword.

Uploaded by

Saranya
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 64

Classes and Objects in Java

Basics of Classes in Java

1
Introduction
 Java is a true OO language and therefore the
underlying structure of all Java programs is classes.

 Classes create objects and objects use methods to


communicate between them.

 A class essentially serves as a template for an object


and behaves like a basic data type “int”.

 It is therefore important to understand how the fields


and methods are defined in a class and how they are
used to build a Java program that incorporates the
basic OO concepts such as encapsulation, inheritance,
and polymorphism.

2
Classes
 A class is a collection of Objects. Objects may be fields
(data) and methods (procedure or function) that operate
on that data.
(Or)
 A class is a blueprint or template from which individual
objects are created.

Circle

centre
radius

circumference()
area()

3
Classes
 A class is a collection of fields (data) and methods
(procedure or function) that operate on that data.
 The basic syntax for a class definition:
class ClassName [extends SuperClassName]
{
[fields declaration]
[methods declaration]
}

 Bare bone class – no fields, no methods

public class Circle


{
// my circle class
}
4
Adding Fields: Class Circle with fields

 Add fields
public class Circle
{
public double x, y; // centre coordinate
public double r; // radius of the circle

 The fields (data) are also called the


instance varaibles.

5
Adding Methods

 A class with only data fields has no life. Objects


created by such a class cannot respond to any
messages.
 Methods are declared inside the body of the
class but immediately after the declaration of
data fields.
 The general form of a method declaration is:
type MethodName (parameter-list)
{
Method-body;
}

6
Adding Methods to Class Circle
public class Circle {

public double x, y; // centre of the circle


public double r; // radius of circle

//Methods to return circumference and area


public double circumference() {
return 2*3.14*r;
}
public double area() {
Method Body
return 3.14 * r * r;
}
}
7
A class can contain any of the following variable types.
 Local variables − Variables defined inside methods,

constructors or blocks are called local variables. The


variable will be declared and initialized within the method
and the variable will be destroyed when the method has
completed.
 Instance variables − Instance variables are variables

within a class but outside any method. These variables


are initialized when the class is instantiated. Instance
variables can be accessed from inside any method,
constructor or blocks of that particular class.
 Class variables − Class variables are variables declared

within a class, outside any method, with the static


keyword(can be used to refer the common property of all objects.)
8
Exp:
public class Dog {
static String animal_type; // Class variable
String breed; // instance variable
int age;
String color;

void barking()
{

}
void hungry()
{
String foodtype; //Local variable
}

void sleeping() {
}
}
9
Data Abstraction

 Declare the Circle class, have created a


new data type – Data Abstraction

 Can define variables (objects) of that


type:

Circle aCircle;
Circle bCircle;

10
Class of Circle cont.
 aCircle, bCircle simply refers to a Circle , not
an object itself.

aCircle bCircle

null null

Points to nothing (Null Reference) Points to nothing (Null Reference)


11
Creating objects of a class

 Objects are created dynamically using the


new keyword.
 aCircle and bCircle refer to Circle objects
aCircle = new Circle(); bCircle = new Circle() ;

12
Creating objects of a class
aCircle = new Circle();
bCircle = new Circle();

bCircle = aCircle;

13
Creating objects of a class
aCircle = new Circle();
bCircle = new Circle() ;

bCircle = aCircle;

Before Assignment After Assignment

aCircle bCircle aCircle bCircle

P Q P Q

14
Automatic garbage collection
Q
 The object does not have a
reference and cannot be used in future.

 The object becomes a candidate for


automatic garbage collection.

 Java automatically collects garbage


periodically and releases the memory
used to be used in the future.

15
Accessing Object/Circle Data
 Syntax for accessing data defined in a
structure.

ObjectName . VariableName
ObjectName .MethodName(parameter-list)

Circle aCircle = new Circle();


aCircle.x = 2.0 // initialize center and radius
aCircle.y = 2.0
aCircle.r = 1.0

16
Executing Methods in Object/Circle

 Using Object Methods:


sent ‘message’ to aCircle

Circle aCircle = new Circle();

double area;
aCircle.r = 1.0;
area = aCircle.area();

17
Using Circle Class
// Circle.java: Contains both Circle class and its user class
//Add Circle class code here
class MyMain
{
public static void main(String args[])
{
Circle aCircle; // creating reference
aCircle = new Circle(); // creating object
aCircle.x = 10; // assigning value to data field
aCircle.y = 20;
aCircle.r = 5;
double area = aCircle.area(); // invoking method
double circumf = aCircle.circumference();
System.out.println("Radius="+aCircle.r+" Area="+area);
System.out.println("Radius="+aCircle.r+" Circumference ="+circumf);
}
}

OUT PUT :
Radius=5.0 Area=78.5
Radius=5.0 Circumference =31.400000000000002

18
Costructors

19
 Constructor in java is a special type of method that is
used to initialize the object.
 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.
Rules for creating java 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
Types of java constructors
There are two types of constructors:
 Default constructor (no-arg constructor)

 Parameterized constructor

20
Example of default constructor
class Bike1{
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}
Output:
Bike is created

21
Example of parameterized constructor
class Student4{
int id;
String name;

Student4(int i,String n){


id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
Output:
111 Karan
222 Aryan

22
this keyword

23
 this is a reference variable that refers to the
current object in java.
 It is a keyword in java language represents
current class object.
 this is always a reference to the object on
which the method was invoked.
 It can be used in side of method or
constructor.

24
Usage of this keyword
 It can be used to refer current class instance variable. { this.x
}
 this() can be used to invoke current class constructor from
another method or constructor.
{ this(); }
 It can be used to invoke current class method (implicitly)
{ this.add() }
 It can be passed as an argument in the method call.
{ add(this);}
 It can be passed as argument in the constructor call.
 It can also be used to return the current class instance.
{ return this; }
25
Why use this keyword in java ?
 The main purpose of using this keyword is to
differentiate the formal parameter and data
members of class.
 whenever the formal parameter and data members
of the class are similar then jvm get ambiguity (no
clarity between formal parameter and member of
the class)
 To differentiate between formal parameter and
data member of the class, the data member of the
class must be preceded by "this".
26
Example without using this keyword
class Employee
{ int id; String name;
Employee(int id,String name)
{ id = id;
name = name;
}
void show()
{ System.out.println(id+" "+name); }
public static void main(String args[])
{ Employee e1 = new Employee(111,"Harry");
Employee e2 = new Employee(112,"Jacy");
e1.show(); e2.show();
}
}
 Output
 0 null 0 null
27
Example with using this keyword
class Employee
{ int id; String name;
Employee(int id,String name)
{ this. id = id;
this. name = name;
}
void show()
{ System.out.println(id+" "+name); }
public static void main(String args[])
{ Employee e1 = new Employee(111,"Harry");
Employee e2 = new Employee(112,"Jacy");
e1.show(); e2.show();
}
}
 Output
 111 Harry 112 Jacy

28
 this: to invoke current class method

29
 this() : to invoke current class constructor
class A{
A(){System.out.println("hello a");}
A(int x){
this();
System.out.println(x);
}
}
class TestThis5{
public static void main(String args[]){
A a=new A(10);
}}
Out put:
hello a
10
30
 Calling parameterized constructor from default
constructor:
class A{
A(){
this(5);
System.out.println("hello a");
}
A(int x){
System.out.println(x);
}
}
class TestThis6{
public static void main(String args[]){
A a=new A();
}}
Out put:
5
31
hello a
 this: to pass as an argument in the
method
class S2{
void m(S2 obj){
System.out.println("method is invoked");
}
void p(){ Hear this refer
m(this); current class object
}
public static void main(String args[]){
S2 s1 = new S2();
s1.p();

} }
Out put:
method is invoked
32
: this keyword can be used to return current class instance

 We can return this keyword as an statement from the


method. In such case, return type of the method must be
the class type (non-primitive). Let's see the example:
 Syntax of this that can be returned as a statement

return_type method_name()
{
return this; Control jump from out
of method
}

33
 //Example of this keyword that you return as a
statement from the method
class ClassMe
{
ClassMe getClassMe()
{ return this; }

void display()
{ System.out.println("Don't confuse"); }
}
class MainClass
{ public static void main(String args[])
{
new ClassMe().getClassMe().display();
}}
Output:
Don't confuse
34
Understanding static
 The static keyword in java is used for
memory management mainly.
The static can be:
 variable (also known as class variable)

 method (also known as class method)

 block

35
1) Java static variable

 If you declare any variable as static, it is known


static variable.
 The static variable can be used to refer the common
property of all objects (that is not unique for each
object) e.g. company name of employees,college
name of students etc.
 The static variable gets memory only once in class
area at the time of class loading.

36
2) 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 object of a

class.
 A static method can be invoked without the need for creating

an instance of a class(object).
 static method can access static data member and can change

the value of it.


Restrictions for static method
 There are two main restrictions for the static method.

They are: The static method can not use non static data
member or call non-static method directly.
 this and super cannot be used in static context.

37
 3) Java static block
 Is used to initialize the static data member.
 It is executed before main method at the time of class loading.

Example of static block

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 38
Overloading Methods or
Constructors

39
 In Java, it is possible to define two or more methods within
the same class that share the same name, as long as their
parameter declarations are different.
 If a class has multiple methods having same name but
different in parameters, it is known as Method
Overloading.
 Method overloading is one of the ways that Java supports
polymorphism.

Advantage of method overloading:


 Method overloading increases the readability of the
program.
40
Different ways to overload the method:
 There are two ways to overload the method

in java
1. By changing number of arguments
2. By changing the data type

41
1) Method Overloading: changing no. of
arguments
class Adder{
static int add(int a,int b)
{return a+b;}
static int add(int a,int b,int c)
{return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
Out put:
22
33 42
2) Method Overloading: changing data type of
arguments
class Adder{
static int add(int a, int b)
{return a+b;}
static double add(double a, double b)
{return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
Out put:
22
43
24.9
Note:
 In java, method overloading is not possible by changing the return type
of the method only because of ambiguity.
 We can also overload java main() method. You can write any
number of main methods in a class by method overloading. But JVM calls
main() method which receives string array as arguments only. Let's see
the simple example:
 If there are matching type(int & long) arguments in the method, type
promotion is not performed.
 We can also overload constructor methods
Exp:
class TestOverloading4{
public static void main(String[] args){System.out.println("main with String[]");}
public static void main(String args){System.out.println("main with String");}
public static void main(){System.out.println("main without args");}
}
Out put:
main with String[]
44
Using Object as Parameter
class Rectangle
{
int length; int width;
Rectangle(int l, int b)
{
length = l; width = b;
}
void area(Rectangle obj)
{ int areaOfRectangle = obj.length * obj.width;
System.out.println("Area of Rectangle : " + areaOfRectangle);
}}
class RectangleDemo
{ public static void main(String args[])
{ Rectangle r1 = new Rectangle(10, 20);
Rectangle r2 = new Rectangle(20, 30);
r1.area(r1); r2.area(r2);
}}
Output of the program : 200 45
Argument Passing
 In general, there are two ways that a
computer language can pass an argument.
1. call-by-value(pass values).
2. call-by-reference(pass object).
 Java also use above two ways to pass an
argument.
 When you pass a primitive type to a method,
it is passed by value
 When you pass an object to a method, it is
call-by-reference
46
// Primitive types are passed by value .(call by value)
class Test {
void meth(int i, int j)
{
i *= 2;
j /= 2;
}
}
class CallByValue {
public static void main(String args[]) {
Test ob = new Test();
int a = 15, b = 20;
System.out.println("a and b before call: " +
a + " " + b);
ob.meth(a, b);
System.out.println("a and b after call: " +
a + " " + b);
}
}
The output from this program is shown here:
a and b before call: 15 20
a and b after call: 15 20 47
// Objects are passed through their references (call by reference).
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
// pass an object
void meth(Test o) {
o.a *= 2;
o.b /= 2;
} }
class PassObjRef {
public static void main(String args[]) {
Test ob = new Test(15, 20);
System.out.println("ob.a and ob.b before call: " +
ob.a + " " + ob.b);
ob.meth(ob);
System.out.println("ob.a and ob.b after call: " +
ob.a + " " + ob.b);
}
}
This program generates the following output:
ob.a and ob.b before call: 15 20
ob.a and ob.b after call: 30 10 48
Recursion
 Java supports recursion.
 Recursion is the process of defining
something in terms of itself
 Java programming, recursion is the attribute
that allows a method to call itself.
 A method that calls itself is said to be
recursive.

49
// A simple example of recursion.
class Factorial {
// this is a recursive method
int fact(int n) {
int result; The output from this program is
if(n==1) return 1; shown here:
result = fact(n-1) * n;
//fact(3-1)*3->fact(2-1)*2*3->1*2*3 Factorial of 3 is 6
return result; Factorial of 4 is 24
Factorial of 5 is 120
}
}
class Recursion {
public static void main(String args[]) {
Factorial f = new Factorial();
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}
}
50
Access Control
 Access means visibility, if you do not have
access to a class you cannot use any
methods or variables of that class.
 Java provide Access Modifiers to access
class.
 There are two types of modifiers that can be
used for class declaration
 Access Modifiers - public and default
(package)
 Nonaccess Modifiers - final and abstract
51
Access Modifiers
Access Modifier Class or member can be
referenced by…
public methods of the same class, and
methods of other classes
private methods of the same class only

protected methods of the same class, methods


of subclasses, and methods of
classes in the same package
default No access methods in the same package only
modifier (package
access)
Exploring the String Class

53
Exploring the String Class
 Java does not support String type, it is not a
simple type .
 String is an array of characters.It is under the
package java.lang.*;
 In java String is an “Object”.
 Strings in java are immutable
 Once created they cannot be altered and hence
any alterations will lead to creation of new string
object
 String is thread safe. It can not be used by two
threads simultaneously
Note: Object is the super class for all classes in java
54
 String s1 = “Example”
 String s2 = new String(“Example”)
 String s3 = “Example”
 The difference between the three statements is that, s1
and s3 are pointing to the same memory location i.e. the
string pool . s2 is pointing to a memory location on the
heap.
 Using a new operator creates a memory location on the
heap.
 Concatenating s1 and s3 leads to creation of a new string
in the pool.

55
StringBuffer

A StringBuffer is like a String, but can be modified.
 The length and content of the StringBuffer sequence can
be changed through certain method calls.
 StringBuffer can not be used by two threads
simultaneously.
 StringBuffer defines three constructors:
 StringBuffer(), StringBuffer(int size), StringBuffer(String str)
public class mybuffers{
public static void main(String args[]){
StringBuffer buffer = new StringBuffer(“Hi”);
buffer.append(“Bye”);
System.out.println(buffer);
}
}
 This program appends the string Bye to Hi and prints it to the screen.
56
StringBuilder
 StringBuilder is same as the StringBuffer , that is it
stores the object in heap and it can also be
modified .
 The main difference between the StringBuffer and
StringBuilder is that StringBuilder is not thread
safe .
 The StringBuilder class is not synchronized
 StringBuilder is fast as it is not thread safe .
 StringBuilder allow two threads to simultaneously
access the same method.

57
class StringBuilderExample{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
sb.append("Java");//now original string is changed.
System.out.println(sb);//prints Hello Java.
}
}

58
// Demonstrating Strings.
class StringDemo {
public static void main(String args[]) {
String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1 + " and " + strOb2;
System.out.println(strOb1);
System.out.println(strOb2);
System.out.println(strOb3);
}
}
The output produced by this program is shown here:
First String
Second String
First String and Second String

59
// Demonstrating some String methods.
class StringDemo2 {
public static void main(String args[]) {
String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1;
System.out.println("Length of strOb1: " +strOb1.length());
System.out.println("Char at index 3 in strOb1: " +strOb1.charAt(3));
if(strOb1.equals(strOb2))
System.out.println("strOb1 == strOb2");
else
System.out.println("strOb1 != strOb2");
if(strOb1.equals(strOb3))
System.out.println("strOb1 == strOb3");
else
System.out.println("strOb1 != strOb3");
}
}
This program generates the following output:
Length of strOb1: 12
Char at index 3 in strOb1: s
strOb1 != strOb2
strOb1 == strOb3

60
// Demonstrate String arrays.
class StringDemo3 {
public static void main(String args[]) {
String str[] = { "one", "two", "three" };
for(int i=0; i<str.length; i++)
System.out.println("str[" + i + "]: " +
str[i]);
}
}
Here is the output from this program:
str[0]: one
str[1]: two
str[2]: three
61
public class ConcatenationExample
{ public static void main(String args[])
{ //One way of doing concatenation
String str1 = "Welcome";
str1 = str1.concat(" to ");
str1 = str1.concat(" String handling ");
System.out.println(str1); //Other way of doing
concatenation in one line
String str2 = "This";
str2 = str2.concat(" is").concat(" just a").concat(" String");
System.out.println(str2);
String str3=str1.concat(str2) } }
Output:
 Welcome to String handling
 This is just a String
 Welcome to String handling This is just a String
62
Using Command-Line Arguments
 We will pass information into a program when you
run it. This is accomplished by passing command-
line arguments to main( ).
// Display all command-line arguments.
class CommandLine {
public static void main(String args[]) {
for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]: " +
args[i]);
}
}
63
 Try executing this program, as shown here:
 java CommandLine this is a test 100 -1

 When you do, you will see the following

output:
args[0]: this
args[1]: is
args[2]: a
args[3]: test
args[4]: 100
args[5]: -1
64

You might also like