0% found this document useful (0 votes)
22 views31 pages

CJP Unit-4

java unit 4

Uploaded by

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

CJP Unit-4

java unit 4

Uploaded by

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

Object Oriented Programming -I (3140705)

Unit-04
Objects and Classes

Computer Engineering Department


Darshan Institute of Engineering & Technology, Rajkot
[email protected]
9624822202
 Outline
Looping

 Class
 Object
Class
 Class is derived datatype, it combines members of different datatypes into one.
 Defines new datatype (primitive ones are not enough).
 For Example : Car, College, Bus etc..
 This new datatype can be used to create objects.
 A class is a template for an object .
Example :
class Car{
String company;
String model;
double price;
double milage;
………
}

Prof. Arjun V. Bala #3140705 (OOP-I)  Unit 04 – Object and Class 3


Car Class

Class: Car

Properties (Describe)
Company
Model Methods (Functions)
Color Start
Mfg. Year Drive
Price Park
Fuel Type On_break
Mileage On_lock
Gear Type On_turn
Power Steering
Anti-Lock braking system
Prof. Arjun V. Bala #3140705 (OOP-I)  Unit 04 – Object and Class 4
Object
 An object is an instance of a class.
 An object has a state and behavior.
Example: A dog has
states - color, name, breed as well as
behaviors – wagging the tail, barking, eating.
 The state of an object is stored in fields (variables), while methods (functions) display the
object's behavior.

Prof. Arjun V. Bala #3140705 (OOP-I)  Unit 04 – Object and Class 5


Objects of Class Bird

Prof. Arjun V. Bala #3140705 (OOP-I)  Unit 04 – Object and Class 6


Objects of a class Car

Honda City Hyundai i20 Sumo Grand

Mercedes E class Swift Dzire

Prof. Arjun V. Bala #3140705 (OOP-I)  Unit 04 – Object and Class 7


Rectangle Class
 Properties in rectangle Class
 length
 width
 borderColor
 backgroundColor

length = 3
length = 5 length = 5
width = 3
width = 2 width = 2
borderColor=red
borderColor=black borderColor=none
backgroundColor=
backgroundColor=white length = 2 backgroundColor=yellow
white
width = 5
borderColor=black
backgroundColor=
white

Prof. Arjun V. Bala #3140705 (OOP-I)  Unit 04 – Object and Class 8


Creating Object & Accessing members
 new keyword creates new object
 Syntax:
ClassName objName = new ClassName();
Example :
SmartPhone iPhone = new SmartPhone();
 Object variables and methods can be accessed using the dot (.) operator
 Example:
iPhone.storage = 8000;

Prof. Arjun V. Bala #3140705 (OOP-I)  Unit 04 – Object and Class 9


class Box {
double length;
length = 10
length
double breadth;
double height; myBox1
} breadth = 20
breadth
class BoxDemo {
public static void main(String args[]) { height = 30
height
Box myBox1 = new Box();
Box myBox2 = new Box();
double vol;
length= 3
length
myBox1.length = 10;
myBox1.breadth = 20; myBox2 breadth
breadth
=6
myBox1.height = 30;
height
height= 9
myBox2.length = 3;
myBox2.breadth = 6;
myBox2.height = 9;

vol = myBox1.length * myBox1.breadth * myBox1.height;


System.out.println("Volume is " + vol);
vol = myBox2.length * myBox2.breadth * myBox2.height;
System.out.println("Volume is " + vol);
}
}
Prof. Arjun V. Bala #3140705 (OOP-I)  Unit 04 – Object and Class 10
Introducing methods
 Methods represents the behavior of a class.
 Remember : a Method is always invoked relative to an object. (except ….)
 Syntax:
access_specifier return_type method_name(argument_list)
{
// code
}

Prof. Arjun V. Bala #3140705 (OOP-I)  Unit 04 – Object and Class 11


Example (method)
public class SmartPhone {
String manufacturer;
String model;
double storage;
double screenSize;
public String getManufacturer(){
return manufacturer;
}
public void setManufacturer(String a){
manufacturer = a;
}
}
public class Demo {
public static void main(String args[]) {
SmartPhone sp = new SmartPhone();
sp.setManufacturer("Samsung");
String name = sp.getManufacturer();
System.out.println(name);
}
}

Prof. Arjun V. Bala #3140705 (OOP-I)  Unit 04 – Object and Class 12


Constructor
 A constructor is a “special” member method which initializes the objects of class.

Properties of constructor:
 Constructor is invoked automatically whenever an object of class is created.
 Constructor name must be same as class name.
 Constructors do not have return types and they cannot return values, not even void.
 All classes have constructors by default: if you do not create a class constructor yourself, Java
creates one for you. However, then you are not able to set initial values for object attributes.
 Types of Constructor
1. Default Constructor
2. Parameterized Constructor

Prof. Arjun V. Bala #3140705 (OOP-I)  Unit 04 – Object and Class 13


Default Constructor
 Default constructor is the one which invokes by default when object of the class is created.
 It is generally used to initialize the default value of the data members.
 It is also called no argument constructor.
class Rect{ public class RectDemo{
int len; public static void main(String[] args) {
int wid; Rect r1 = new Rect();
boolean isFilled; System.out.println(r1.len);
}
public Rect(){ }
len = 6;
wid = 6;
isFilled = false;
}
}

Prof. Arjun V. Bala #3140705 (OOP-I)  Unit 04 – Object and Class 14


Parameterized Constructor
 Constructors that can take arguments are called parameterized constructors.
 Sometimes it is necessary to initialize the various data elements of different objects with
different values when they are created.
 We can achieve this objective by passing arguments to the constructor when the objects are
created.
class Rect{ public class RectDemo{
int len; public static void main(String[] args) {
int wid; Rect r1 = new Rect(6,6,false);
boolean isFilled; System.out.println(r1.len);
}
public Rect(int l, int w, boolean isF){ }
len = l;
wid = w;
isFilled = isF;
}

Prof. Arjun V. Bala #3140705 (OOP-I)  Unit 04 – Object and Class 15


this keyword
 this is a reference variable that refers to the current object.
 this can be used to invoke current object's method.
 this() can be used to invoke current class constructor
 this can be passed as a parameter to constructor and method call.
 this can be used to return the current object from the method.

Prof. Arjun V. Bala #3140705 (OOP-I)  Unit 04 – Object and Class 16


class Box {
double length;
double breadth;
double height;
Box(double
Box(double length, l, double b, breadth,
double double h) double{ height) {
System.out.println("Constructing Box");
this.length
length
length l;= length;
== length; length is instance variable as well
this.breadth =
breadth == breadth;breadth; Creates ambiguity for compiler
breadth b; as length is formal parameter of
this.height
height =
height = h; =
height;height; method
}
void volume() {
double volume = length * breadth * height;
System.out.println("Volume is " + volume);
}
}
class BoxDemo {
public static void main(String args[]) {
Box myBox1 = new Box(10,20,30);
Box myBox2 = new Box(3,6,9);
myBox1.volume();
myBox2.volume();
}
} Prof. Arjun V. Bala #3140705 (OOP-I)  Unit 04 – Object and Class 17
Understanding the Scope of Variable

Prof. Arjun V. Bala #3140705 (OOP-I)  Unit 04 – Object and Class 18


Method Overloading
public class OverloadingMethods {
 Overloading allows different public static void main(String[] ar) {
methods to have same name, int ans1 = sum(5,2); // will return 7
but different signatures. int ans2 = sum(5,2,6); // will return 13
double ans3 = sum(5.8,6.4); // will return 12.2
 Signature can differ by number // print ans1,ans2,ans3 in order to see the result
of input parameters or type of }
input parameters or both. // Overloaded sum(). This sum takes two int parameters
public static int sum(int x, int y) {
 Overloading is related to return (x + y);
compile time (or static) }
polymorphism. // Overloaded sum(). This sum takes three int parameters
public static int sum(int x, int y, int z) {
return (x + y + z);
}
// Overloaded sum(). This sum takes two double
parameters
public static double sum(double x, double y) {
return (x + y);
}
}
Prof. Arjun V. Bala #3140705 (OOP-I)  Unit 04 – Object and Class 19
static keyword
 static keyword is mainly used for memory management.
 It can be used with
 Variables
 Methods
 Blocks
 Nested classes
 Basically, static is used for a constant variable or a method that is same for every instance of a
class.
 The static variable can be used to refer to the common property of all objects.
 The static variable gets memory only once in the class area at the time of class loading.
 It makes your program memory efficient.
 Syntax
static type variablename;

Prof. Arjun V. Bala #3140705 (OOP-I)  Unit 04 – Object and Class 20


class Student {
int rollNo;
String name;
static String
String collegecollege = "DIET";
= "DIET";
.
.
.
}
class StudentDemo {
public static void main(String args[]) {
Student student1 = new Student();
Student student2 = new Student();
Student student3 = new Student();
.
. student1 student2 student3
.
rollNo
}
}
name

college DIET DIET DIET

college DIET
Prof. Arjun V. Bala #3140705 (OOP-I)  Unit 04 – Object and Class 21
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.
 Restrictions
1. The static method can not use non static data member or call non-static method directly.
2. this and super cannot be used in static context.

Prof. Arjun V. Bala #3140705 (OOP-I)  Unit 04 – Object and Class 22


class Student {
int rollno;
String name;
static String college="abc";
static void change() {
college = "DIET"; We can not use non-static
rollno = 10; variables in static methods
}
Student(int r, String n) {
rollno = r;
name = n;
}
void display() {
System.out.println(rollno+" "+name+" "+college);
}
}
class TestStaticMethod {
public static void main(String args[]) {
Student.change();
Student s1 = new Student(111,"Tom");
Student s2 = new Student(222,"Jerry");
s1.display();
s2.display();
}
} Prof. Arjun V. Bala #3140705 (OOP-I)  Unit 04 – Object and Class 23
static block
 static block is executed exactly once, when the class is first loaded.
 It is used to initialize static variables of the class.
 It will be executed even before the main method.
 Syntax:
static {
//initialisation of static variables…
}

Prof. Arjun V. Bala #3140705 (OOP-I)  Unit 04 – Object and Class 24


Mutable and Immutable
 The content of mutable object can be changed, while content of immutable objects can not be
changed.
class MutableClass{ class ImmutableClass{
int a; int a;
void add5() { int add5() {
a = a + 5; return ( a + 5 );
} }
} }
public class MutableClassDemo { public class MutableClassDemo {
public static void main(String[] args) { public static void main(String[] args) {
MutableClass m1 = new MutableClass(); ImmutableClass m1 = new ImmutableClass();
m1.a = 10; m1.a = 10;
m1.add5(); int ans = m1.add5();
System.out.println(m1.a); System.out.println("A in m1 = " + m1.a);
} System.out.println("returned = " + ans);
} }
}

Prof. Arjun V. Bala #3140705 (OOP-I)  Unit 04 – Object and Class 25


Passing Objects as Argument
 In order to class Time{
int hour;
understand how int minute;
and why we need to int second;
pass object as an
public Time(int hour, int minute, int second) {
this.second = second;
argument in this.minute = minute;
methods, lets see this.hour = hour;
}
the below example. void add(Time t) { public class TimeDemo {
this.second += t.second; public static void main(String[] args) {
if(this.second>=60) { Time t1 = new Time(11,59,55);
this.minute++; Time t2 = new Time(0,0,5);
this.second-=60;
} t1.add(t2);
this.minute += t.minute;
if(this.minute>=60) { System.out.println(t1.hour + ":" +
this.hour++; t1.minute + ":" + t1.second);
this.minute-=60; }
} }
this.hour += t.hour;
}
}
Prof. Arjun V. Bala #3140705 (OOP-I)  Unit 04 – Object and Class 26
Array of Objects
 We can create an array of object in java.
 Similar to primitive data type array we can also create and use arrays of derived data types
(class).
class Student{ public class ArrayOfObjectDemo {
int rollNo; public static void main(String[] args) {
String name; Student[] stu = new Student[3];

public Student(int rollNo, String name) { stu[0] = new Student(101,"darshan");


this.rollNo = rollNo; stu[1] = new Student(102,"arjun");
this.name = name; stu[2] = new Student(103,"java");
}
stu[0].printStudentDetail();
void printStudentDetail() { stu[1].printStudentDetail();
System.out.println("| "+ stu[2].printStudentDetail();
rollNo }
+" | -- | "+ }
name +" |");
}
}
Prof. Arjun V. Bala #3140705 (OOP-I)  Unit 04 – Object and Class 27
Package (Not part of this Unit)
 A Package can be defined as a grouping of related types providing access protection and name
space management.
 Programmers can define their own packages to bundle group of classes/interfaces, etc.
 Packages are used in Java in order to
1. prevent naming conflicts
2. control access,
3. make searching/locating of classes/interfaces easier.
 It is a good practice to group related classes implemented so that a programmer can easily
determine that the classes, interfaces are related.

Prof. Arjun V. Bala #3140705 (OOP-I)  Unit 04 – Object and Class 28


Creating a package
 To create a package you need to write package statement followed by the name of the package.
 Syntax : package package_name;
 Example :
package darshan_student;

class Student {
// code
}
 The package statement should be the first line in the source file.
 There can be only one package statement in each source file, and it applies to all types in the file.
 If a package statement is not used then the class/interfaces will be put into an unnamed
package.

Prof. Arjun V. Bala #3140705 (OOP-I)  Unit 04 – Object and Class 29


Package (Example)
package myPackage;
public class Animal {
public String name;
public void eat(){
System.out.println("Organic Food !!!!");
}
public static void main(String[] args){
Animal a = new Animal();
a.eat();
}
}
.
Represent the current directory
 To compile
javac –d . Animal.java
 To Run the class file
java myPackage.Animal

Prof. Arjun V. Bala #3140705 (OOP-I)  Unit 04 – Object and Class 30


Programs
 Write a class named Rectangle to represent a rectangle. It contains following members:
Data: width (double) and height (double) that specify the width and height of the rectangle.
Methods:
1. A no-arg constructor that creates a default rectangle.
2. A constructor that creates a rectangle with the specified width and height.
3. A method named getArea() that returns the area of this rectangle.
4. A method named getPerimeter() that returns the perimeter.
 Write a program to create circle class with area function to find area of circle.
 Define time class with hour and minute. Also define addition method to add two time objects.
 Declare a class called student having following data members:id_no,
no_of_subjects_registered, subject_code, subject_credits,
grade_obtained and spi. Define constructor and calculate_spi methods. Define main
to instantiate an array for objects of class student to process data of n students.

Prof. Arjun V. Bala #3140705 (OOP-I)  Unit 04 – Object and Class 31

You might also like