Sie sind auf Seite 1von 67

JAVA

Classes and Objects


KLN Classes and Objects
Classes and Objects

Classes reflect concepts, objects reflect instances that


represent these concepts.

object class Girl

Sony Leena Alina Jssica


K. Lakshmi Narayana 2
KLN Classes and Objects

Objects and Classes example

Operations/Methods
Class BankAccount MakeDesposit
Balance Transfer
Interest
WithDraw
Owner
Account_number GetBalance

Balance 500 Balance 10,000


10% 12%
Tom Alina
09112 08345

K. Lakshmi Narayana 3
KLN Classes and Objects

Classes

The class defines a new data type, this new type can be used to
create objects of that type.

A class denotes a category of objects, and acts as a blueprint (or


template) for creating such objects.

All the java statements, method definitions and method calls are
inside the class only including main method.

 A Java Program can have at most one public class or interface.

K. Lakshmi Narayana 4
KLN Classes and Objects

Classes and Atributes


Class Syntax:
<class modifiers> class <class name><formal type parameter list>
<extends clause> <implements clause> // Class header
{ // Class body
<field declarations>
<method declarations>
<nested class declarations>
<nested interface declarations>
<nested enum declarations>
The member declarations,
<constructor declarations> constructor declarations,
<initializer blocks> and initializer blocks can
} // No semicolon is required appear in any order in the
class body.
K. Lakshmi Narayana 5
KLN Classes and Objects
Classes
The class header can specify the following information:
 Accessibility modifier i.e. public, protected and private (If the
accessibility modifier is omitted, then it is called package or default
accessibility)
 Additional class modifiers (The modifiers abstract and final can be
applied to top-level and nested classes).
 A formal type parameter list, if the class is generic

 A class can extends only one class and implements


any number of interfaces
All programs import Object class is the Parent
java.lang package by default of all the Java classes by default.
K. Lakshmi Narayana 6
KLN Classes and Objects

Objects
 An object is an instance of a class.
 The process of creating objects from a class is called instantiation.
 Objects enhance software reusability. Once a class is defined, we can
create any number of objects of the same type.
 C++ objects can be created with class name followed by an
object name.
 In Java we can create an object with the reference and new
operator (Java reference is not same as C++ reference).

A class is a logical construct and an object has physical reality.

K. Lakshmi Narayana 7
KLN Classes and Objects
Java Object Creation
Obtaining an object of a class in Java is a two-step process.
 First you must create a reference variable of the class type.
 Second you must acquire actual, physical copy of the object and assign it
to that reference variable. This can be done by using new operator.
The operator new creates a new object of the class specified to the right of the keyword.
Box mybox; mybox
null width
mybox=new Box(); height
mybox
depth
Box Object
The first line declares mybox as a reference type. After this line executes, mybox
contains the null value, which indicates it does not point to any object. Any
attempt to use mybox results in a compile error. The next line allocates an actual
object and assigns a reference to it to mybox. Now you can use mybox as Box object.

Object creation using single line: Box mybox=new Box();


K. Lakshmi Narayana 8
KLN Classes and Objects
Object Creation Cont..
Student s1 = new Student( );
class Student
define a variable
{ create a new
s1 to refer to a
Student object
private long rollNum; Student object
private String name = “empty”;
private static classStrength;
}
In java objects are created with new.
 Runtime system will allocate enough memory to store the new object

 If space is not enough, automatic garbage collector will reclaim


space from unused objects, otherwise an OutOfMemoryError
exception will be thrown.
The new allocates memory for The new operator dynamically
an object during run time. allocates memory for an object
K. Lakshmi Narayana 9
KLN Classes and Objects
Difference between class and Object
Class Object
Class is blue print of an object, Object is instance of class, which is
which is non-live entity. For live entity. For example James, SBI
example employee, bank etc. etc.
A class is a user defined data type An object is a programming
used to implement an abstract structure that groups related
object, giving us the capability to methods and the data. It is also
use OOP with java. A class include known as instance of class.
members.
Class is the template for members Object is the physical reality to
and methods. access the members and methods.
Class contains any no of objects. Object is basic runtime entity of
class. Object belongs to single class.
K. Lakshmi Narayana 10
KLN Classes and Objects

Memory for Reference and Objects

When you are executing a java program then JVM executes two
memory blocks for program execution.

 Executing stack memory


 Heap memory

 References and native data types are allocated in memory is called


Stack memory.

 Objects are allocated in memory is called Heap memory.

K. Lakshmi Narayana 11
KLN Classes and Objects
Life Cycle of Objects

Here Sample is a class. Stack HEAP


Sample x;
x

K. Lakshmi Narayana 12
KLN Classes and Objects

Life Cycle of Objects


Stack HEAP
Sample x ;
x = new Sample(); x 1 reference

K. Lakshmi Narayana 13
KLN Classes and Objects
Life Cycle of Objects
Stack HEAP
Sample x ;
x = new Sample(); x 1 reference

Sample y = new Sample();


y

1 reference

K. Lakshmi Narayana 14
KLN Classes and Objects

Life Cycle of Objects


Stack HEAP
Sample x ;
z
x = new Sample(); x 2 references

Sample y = new Sample();


y
Sample z= x; 1 reference

K. Lakshmi Narayana 15
KLN Classes and Objects

Life Cycle of Objects


Stack HEAP
Sample x ;
z
x = new Sample(); x 1 reference

Sample y = new Sample();


y
Sample z= x;
2 references

z = y;

K. Lakshmi Narayana 16
KLN Classes and Objects

Life Cycle of Objects


Stack HEAP
Sample x ;
z
x = new Sample(); x 0 references
(eligible for GC)
Sample y = new Sample();
y
Sample z= x;
2 references
z = y;
x = null;

K. Lakshmi Narayana 17
KLN Classes and Objects
Life Cycle of Objects
Stack HEAP
Sample x ;
x = new Sample(); z
x 0 references
Sample y = new Sample(); (eligible for GC)

Sample z= x; y 1 reference

z = y;
x = null; 2 references

x = new Sample();

K. Lakshmi Narayana 18
KLN Classes and Objects

Life Cycle of Objects

Sample x ; Stack HEAP


x = new Sample();
z
Sample y = new Sample(); x 0 references
(eligible for GC)
Sample z= x; y 1 reference

z = y;
x = null;
x = new Sample(); 0 references
(eligible for GC)

z=null;
y=null;
K. Lakshmi Narayana 19
KLN Method Declarations Classes and Objects

Syntax:
<method modifiers> <formal parameter list> <return
type> <method name>
(<formal parameter list>) <throws clause> // Method header
{ // Method body
<local variable declarations>
<nested local class declarations>
<statements>
}
The method header can specify the following information:
• Method modifiers are private, protected, public or default.
• Additional method modifiers(i.e. static, final, abstract, synchronized, strictfp, native,
annotation, transient, and volatile)
• A formal parameter list is a comma-separated list of parameters, where each
parameter is a simple variable declaration consisting of its type and name.
<parameter modifier> <type> <parameter name>
• checked exceptions thrown by the method are specified in a throws clause
K. Lakshmi Narayana 20
20
KLN Classes and Objects
Accessing Object Members
 The “dot” notation: <object> • <member>
 This is used to access object members including attributes and methods

Example:
// Accessing the member variables through member functions
obj1.setX(2912);
// Accessing the member variables directly if x is public
obj1.y = 2912;
// Accessing the methods
obj1.display();
The object will continue to exist as long as there is a reference to
it somewhere in your program. When there are no references to
it, the object will be reclaimed to garbage collection.
K. Lakshmi Narayana 21
KLN Classes and Objects

Access Modifiers
public keyword
All the classes, member variables and methods declared with this
keyword are accessible to other classes and other packages.
A public class, variable or method may be used in any program without
restriction.

protected keyword
All the member variables and methods declared with this keyword
are accessible to all the classes in the same package and to subclasses
of that class within the same or other packages.
Also available to all sub-classes of the class that owns the protected
feature.
Only variables and methods may be declared protected.
K. Lakshmi Narayana 22
KLN Classes and Objects

Access Modifiers
Package Access Modifier
It is the name of access types of class, variable and method if you do
not specify any access modifiers. It allows accessibility to any class in
the same package.

private keyword
All the member variables and methods declared with this keyword
are accessible to it’s own class only i.e., specifying a member as
private makes it not accessible to any other classes.

If you want to access the methods from outside the class don’t keep
it in private section.

Top level class may not be declared private


K. Lakshmi Narayana 23
KLN Classes and Objects

private Member Variables


private class Complex { //Remove private
private double real, imaginary;
public Complex(double r, double i) { real = r; imaginary = i; }
private Complex add(Complex c) { //Remove private
return new Complex(real + c.real, imaginary + c.imaginary);
}
public void printComplex() {
System.out.println("Real val = " + real + ", imaginary val = " + imaginary);
}
}
class ComplexAddition {
public static void main(String arg[]) {
Complex c1 = new Complex(1,2);
Complex c2 = new Complex(3,4);
Complex c3 = c1.add(c2);
c3.printComplex();
//double d= c3.real; //ERROR cannot access the private data
}
K. Lakshmi
} Narayana Real val = 4.0, imaginary val = 6.0 24
KLN Classes and Objects

Method Access Level


Most Restrictive
only the class it self
private
All classes inside the same package

default
All classes inside the same package
and derived classes of any package.

protected
Any classes

Default access is enforced when neither


the public, protected nor private access public
modifier is specified in the declaration.
K. Lakshmi Narayana Least Restrictive 25
KLN Classes and Objects
Package Access Modifier
package kln.java;
public class A { int x; }
package kln.java;
public class B {
void foo(A a) { a.x; } // OK, same package
}

package kln.scjp;
public class B {
void foo(A a) { a.x; } // Not OK, different package
}
package kln.java.cse;
public class B {
void foo(A a) { a.x; } // Not OK, different package
}
package kln;
public class B {
void foo(A a) { a.x; } // Not OK, different package
}
K. Lakshmi Narayana 26
KLN Classes and Objects
Protected Access Modifier
public class A {
protected int x;
}

public class B extends A {


void foo(A a) { this.x; a.x; } // OK, B is a decendent of A
}

public class C extends B {


void foo(A a) { this.x; a.x; } // OK, C is a decendent of A through B
}

package edu; // Uh oh!


public class D extends C {
void foo(A a) { this.x; a.x; } // OK, D is a decendent of A through C & B
}

public class E {
void foo(A a) { this.x; a.x; } // ERROR, E is NOT a decendent of A
}
K. Lakshmi Narayana 27
KLN Classes and Objects
Access Modifier Example i = 10, j = 20, and k = 30
class A Value of j = 50
{ private int i=10; public int j=20;
Value of k = 100
int k=30;
public void print()
{ System.out.println("i = " +i+", j = " +j+", and k = " +k);
}
}
class AccessModifiers
{ public static void main(String[] args)
{ A a1=new A();
//a1.i=50; //Private members cannot be accessed
a1.print();
a1.j=50; a1.k=100;
System.out.println("\nValue of j = " +a1.j);
System.out.println("\nValue of k = " +a1.k);
}
}
K. Lakshmi Narayana 28
KLN Default, public and private modifiers Classes and Objects

class Test {
int a; // default access
public int b; // public access
private int c; // private access
void setc(int i) { c = I; } // methods to access c
int getc() { return c; } // get c's value
}
class AccessTest {
public static void main(String args[])
{ Test ob = new Test();
// These are OK, a and b may be accessed directly
ob.a = 10; ob.b = 20;
// ob.c = 100; // Error!
ob.setc(100); // Access member c with methods is OK
System.out.println("a, b, and c: “+ob.a+" “+ob.b+" "+ ob.getc());
}
}
K. Lakshmi Narayana
a, b, and c: 10 20 100
29
KLN Classes and Objects

Accessibility Criteria
Default
Private Protected Public
No Modifier

Same class YES YES YES YES

Same Package Derived /


NO YES YES YES
Non-Derived class

Different Package
NO NO YES YES
Derived class

Different Package
NO NO NO YES
Non-Derived class
K. Lakshmi Narayana 30
KLN Classes and Objects
Rectangle Class without using Methods
import java.util.*;
class Rectangle
{ private int l, b;
public static void main(String args[])
{ Rectangle r1 = new Rectangle();
Scanner sc=new Scanner(System.in);
System.out.print("Enter the r1 Length and Width :: ");
r1.l= sc.nextInt(); r1.b= sc.nextInt();
System.out.println("Area = " + r1.l * r1.b);
System.out.println("Perimeter = " + 2*(r1.l+r1.b));
}
}
K. Lakshmi Narayana 31
KLN Classes and Objects
Rectangle Class with Methods Ver-1

class Rectangle
{ private int len, width;
private Rectangle(int x, int y){ len=x; width=y; } //Constructor
private int area(){ return (len*width); }
private int per(){ return 2*(len+width); }
public static void main(String args[])
{ Rectangle r = new Rectangle(10, 8);
System.out.println("Perimeter = " + r.area());
System.out.println("Perimeter = " + r.per());
}
}
K. Lakshmi Narayana 32
KLN Classes and Objects
Rectangle Class with Methods Ver-2
1) In java we can define more than one class.
2) We can define at most one public class.
3) If java file is having a public class then filename must be the
same as that public class name.

class Rectangle
{ private int len, width;
Rectangle(int x,int y){ len=x;width=y; }
int area(){ return (len*width); }
int per(){ return 2*(len+width); }
}
class MyRectangle
{ public static void main(String args[])
{ Rectangle r = new Rectangle(10, 5);
System.out.println("Perimeter = " + r.area());
System.out.println("Perimeter = " + r.per());
}
K.}Lakshmi Narayana 33
KLN Classes and Objects
Rectangle Class with Methods Ver-3
class Rectangle
{ private int len, width;
Rectangle(int x,int y){ len=x;width=y; }
int area(){ return (len*width); }
Rectangle.java
int per(){ return 2*(len+width); }
}
class MyRectangle
{ public static void main(String args[])
MyRectangle.java
{ Rectangle r = new Rectangle(10, 5);
System.out.println("Perimeter = " + r.area());
System.out.println("Perimeter = " + r.per());
}
}
K. Lakshmi Narayana 34
KLN Rectangle Class in different packages Ver-4
Classes and Objects

package kln.r1;
public class Rectangle
{ private int len, width;
public Rectangle(int x,int y){ len=x;width=y; }
public int area(){ return (len*width); } Rectangle.java
public int per(){ return 2*(len+width); }
}
package kln.r2;
import kln.r1.*;
class MyRectangle MyRectangle.java
{ public static void main(String args[])
{ Rectangle r = new Rectangle(12, 8);
System.out.println("Area = " + r.area());
System.out.println("Perimeter = " + r.per());
}
}

K. Lakshmi Narayana 35
KLN Classes and Objects
Print the Date in dd/mm/yyyy format
import java.util.*;
public class Today
{ public static void main (String[] args)
{ Date d=new Date();
System.out.println("Today\'s Date : " +d.getDate()
+"/"+(d.getMonth()+1)+ "/"+(d.getYear()+1900));
System.out.println("Time : " +d.getHours()
+":"+d.getMinutes());
}
}

K. Lakshmi Narayana 36
KLN Classes and Objects

The Random Class

 The Random class is part of the java.util package

 It provides methods that generate pseudorandom numbers

 A Random object performs complicated calculations based on a seed


value to produce a stream of seemingly random values

 Random numbers in a range can be generated with

number = shiftingValue + randomNumbers.nextInt( scalingFactor );

K. Lakshmi Narayana 37
KLN Classes and Objects
Random class Example1

// Print the 10 Random numbers below 1000


import java.util.Random;
public class RandaomTest
{ public static void main(String args[ ])
560
{ Random ran = new Random(); // random number generator 257
for(int i = 1; i <= 10; i++ ) //printing 10 numbers 644
842
System.out.println(ran.nextInt(1000)); //here 1000 is the range 644
} 15
321
} 709
435
416
K. Lakshmi Narayana 38
KLN Classes and Objects
Initializing objects with Constructors
Java requires a constructor call for every object that’s created.
Keyword new requests memory from the system to store an object, then
calls the corresponding class’s constructor to initialize the object.

A Constructor is a special method of a class which has same


name as that of a class; has no return type not even void, used to
initialize the instance variables of a class, and gets invoked
automatically as soon as the object of the class is created.

By default, the compiler provides a default (i.e. no argument)


constructor.

Constructor is a block of code that is executed automatically after


creating memory for the object. It is used to initialize the members of
the class.
K. Lakshmi Narayana 39
KLN Classes and Objects

Declaring Constructors
Syntax:
<accessibility modifier> <class name> (<formal parameter list>)
<throws clause> // Constructor header
The default return type of the
{ // Constructor body
constructor is the object of that class
<local variable declarations> type. Where as methods doesn’t
<nested local class declarations> have any default return types.
<statements>
}
Rules of Constructor:
 The constructor name must be the same as the class name.

 It can not have any return type, not even void. The implicit return

type of a class’ constructor is the class type itself.


 No return statement inside the body of a constructor.

 Once you define an augmented constructor, it will hide the default

constructor.
K. Lakshmi Narayana 40
KLN Classes and Objects

Constructor Example
By default constructor return type is object type of that
class Rectangle class. So we no need to keep explicit return type.
{
double len, width;
Rectangle(double l,double w){ len=l;width=w; }
void printArea()
{ System.out.println("Area of the Rectangle = "+len*width); }
}

class MyRectangle
{
public static void main(String args[])
{ //Rectangle r1=new Rectangle(); //ERROR Default constructor not present
Rectangle r = new Rectangle(2.0,3.0); //constructor
System.out.println("Rectangle Length="+r.len+"and Width="+r.width);
r.printArea();
} Rectangle Length = 2.0 and Width = 3.0
} Lakshmi Narayana
K. Area of the Rectangle = 6.0 41
KLN Classes and Objects
Use of this reference

When a local variable has the same name as an instance variable, the local
variable hides the instance variable.
 Use the keyword this to overcome the instance variable hiding.
 this can be used inside any method to refer to the current object.
 this is always a reference to the object on which the method was
invoked.
 This reference can be used to access data members of the current object
on which the method is invoked.
 If we use a data member name inside a method then it is converted as
this.DataMemeberName.

this CANNOT be used in a static methods


K. Lakshmi Narayana 42
KLN Classes and Objects
Use of this reference
class Sample The this reference can’t be used
{ int a=5,b=10; with the local variables.
void print()
{ int b=25; //It hides the instance variable
int c=99; //Local variable
System.out.println("a = " +a);
System.out.println("this.a = " + this.a);
System.out.println("b = " +b);
System.out.println("this.b = " + this.b);
//System.out.println("this.c = " + this.c); //ERROR
}
public static void main(String arg[])
{ new Sample().print();
}
}
K. Lakshmi Narayana 43
KLN Classes and Objects

Classes using this reference


The this reference points to the current object.

class Rectangle
{ int len, width;
Rectangle(int len, int width)
{ this.len=len;
this.width=width;
}
void print( )
{ System.out.println("Length :: "+len+", and Width :: "+ this.width);
}

}
public class MyRectangle
{ public static void main(String arg[])
{ Rectangle r1=new Rectangle(8,6);
r1.print();
}
} Lakshmi Narayana
K. 44
44
KLN Classes and Objects
Constructor overloading
Constructors can also be overloaded similarly as method overloading. So a
class can have N number of constructors using overloading.

Example:
public class Rectangle{
double length=5.6, width;
Rectangle() { }
Rectangle(double length,double width){ this.length=length;
this.width=width; }
void print( ) { System.out.println("length= " + length + ", and width= "+ width); }
public static void main(String [] args)
{ Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle(10, 8);
r1.print(); r2.print();
}
}
K. Lakshmi Narayana 45
KLN Classes and Objects
Copy Constructor
Sometimes a programmer wants to create an exact but separate copy of
an existing object so that subsequent changes to the copy should not
alter the original or vice versa. This is possible by copy constructor.

A constructor can even accept objects as arguments is


known as copy constructor.

A copy constructor is a constructor that creates a new object using


an existing object of the same class and initializes each instance
variable of newly created object with corresponding instance
variables of the existing object passed as argument.

K. Lakshmi Narayana 46
KLN Classes and Objects
Copy Constructor Example
class Rectangle
{ int l, b;
Rectangle(int x, int y) { l=x; b=y; }
void setRect(int x, int y) { l=x; b=y; }
Rectangle(Rectangle obj) //copy constructor
{ System.out.println("Copy Constructor Invoked");
l = obj.l; b = obj.b;
}
int area() { return (l * b); }
}
class CopyConstructor
{ public static void main(String[] args)
{ Rectangle r1 = new Rectangle(8,5);
Rectangle r2= new Rectangle(r1); r1.setRect(10, 6);
System.out.println("Area of First Rectangle : "+ r1.area());
System .out.println("Area of Second Rectangle : "+ r2.area());
}
K. Lakshmi Narayana 47
}
KLN Classes and Objects

scope of variables Example


class Scope
{ public static void main(String args[])
{ int x; // known to all code within main
x = 10;
if(x == 10) { // start new scope
int y = 20; // known only to this block
System.out.println("x and y: "+ x + " " + y); // x, y visible here.
x = y * 2;
}
// y = 100; // Error! y is not known here
System.out.println("x is " + x);
}
} x and y: 10 20
x is 40
K. Lakshmi Narayana 48
KLN Classes and Objects

Instance variables, set and get Methods


class Rectangle
{ private double l, w; //Instance Varaibles
void setRectangle(double a, double b){ l=a; w=b; }
void findarea(){ System.out.println("Area = "+l*w); }
public double getLength() { return l; }
public double getWidth() { return w; }
} If the programmer does not supply any constructors,
the default constructor will present automatically.
class MyRectangle Calling default (no arguments)
{ public static void main(String args[]){ constructor of the class.
Rectangle r = new Rectangle();
r.setRectangle(10, 8);
System.out.println("Length = " + r.getLength()+", and Width = " +
r.getWidth());
r.findarea();
}
K.}Lakshmi Narayana 49
KLN Classes and Objects

Static/class Fields
There is only one copy of the static field for the whole class, and it can be
shared by all the objects of the class, they are also know as class variables,
whereas instance variables are separate copy with each object.

static keyword is used as a modifier on variables, methods, and inner classes

static variables can be accessed directly, through class, and through object
<static_var>
<classname>.< static_var >
<objectname>.< static_var >

Whereas instance variables can only be accessed through objects only.


<objectname>.<instance_var>
Un initialized static variables are initialized with the default values.
K. Lakshmi Narayana 50
KLN Classes and Objects
One copy of Class Variables c1 x value :: 5
c2 x value :: 10
public class MyNumber { c3 x value :: 20
public static int counter = 0;int x; No of Objects created :: 3
public void increment( ) { counter++; }
public MyNumber(int x)
{ this.x=x; increment(); //Calling a Method
}
public static void main(String ar[ ] )
{ MyNumber c1=new MyNumber(5);
MyNumber c2=new MyNumber(10);
MyNumber c3=new MyNumber(20);
System.out.println("c1 x value :: " + c1.x);
System.out.println("c2 x value :: " + c2.x);
System.out.println("c3 x value :: " + c3.x);
System.out.println("No of Objects created :: " +counter);
}
}
Class Attributes are shared among all instances of a class.
Where
K. Lakshmi as instance variables are available with every object.
Narayana 51
KLN Classes and Objects

Static methods

 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 creating

the instance of a class.


 Static methods can access only static variables and static methods.
 Static methods cannot refer to this and super references.
 Static methods cannot be declared as abstract
 A static methods cannot be overridden.

K. Lakshmi Narayana 52
KLN Static variables and methods Classes and Objects

class Sample
{ static int x=5; int y=10;
void welcome() { System.out.println("It is for B.Tech ECE "); }
static void bestWishes()
{ System.out.println("\nThank you for Choosing JAVA Course");
}
public void printValues( )
{ System.out.println("x = " + x + ", and y = " + y);
}
public static void main(String arg[]) throws Exception
{ Sample s=new Sample(); //Object is created
System.out.println("x = " + x);
System.out.println("x = " + s.x);
System.out.println("Through class reference x = " + Sample.x);
System.out.println("y = " + s.y);
K. Lakshmi Narayana 53
KLN Static variables and methods Classes and Objects

//System.out.println("y = " + y); //ERROR


//System.out.println("y = " + Sample.y); //ERROR
bestWishes();
s.printValues();
s.bestWishes();
}
}

K. Lakshmi Narayana 54
KLN Addition of Two Matrices Classes and Objects

import java.util.*;
class MatrixAddition
{ int mat[][]; int rows,cols;
public MatrixAddition() { }
public MatrixAddition(int r, int c)
{ rows=r; cols=c;
mat=new int[rows][cols];
}
public void read()
{ int i, j;
Scanner sc=new Scanner(System.in);
for(i=0;i<rows;i++)
for(j=0;j<cols;j++)
mat[i][j]=sc.nextInt();
}
public void display()
{ int i, j;
for(i=0;i<rows;i++)
{ for(j=0;j<cols;j++)
System.out.print(" "+ mat[i][j]);
System.out.println();
}
K. Lakshmi
} Narayana 55
KLN Addition of Two Matrices Cont.. Classes and Objects

public MatrixAddition add(MatrixAddition m1)


{ MatrixAddition temp=new MatrixAddition(this.rows,this.cols); int j;
for(int i=0;i<rows;i++)
for(j=0;j<cols;j++)
temp.mat[i][j]=this.mat[i][j]+m1.mat[i][j];
return temp;
}
public static void main(String [] args)
{ MatrixAddition m1=new MatrixAddition(3, 3);
MatrixAddition m2=new MatrixAddition (3, 3);
MatrixAddition m3;
System.out.println("Enter the elements of 3X3 Matrix"); m1.read();
System.out.println("Enter the elements of 3X3 Matrix"); m2.read();
System.out.println("Elements of Matrix1 ::"); m1.display();
System.out.println();
System.out.println("Elements of Matrix2 ::"); m2.display();
System.out.println();
m3=m1.add(m2);
System.out.println("Addition of Matrices ::"); m3.display();
}
}
K. Lakshmi Narayana 56
KLN Classes and Objects
Multiply matrices using Function return an array

public class Matrix


{ public static int[][] multiply(int[][] m1, int[][] m2)
{ int m1rows = m1.length; int m1cols = m1[0].length;
int m2rows = m2.length; int m2cols = m2[0].length;
int[][] result = new int[m1rows][m2cols];
if (m1cols != m2rows)
throw new IllegalArgumentException("matrices don't match: "+
m1cols + " != " + m2rows);
for (int i=0; i< m1rows; i++)
{ for (int j=0; j< m2cols; j++)
{ for (int k=0; k< m1cols; k++)
result[i][j] += m1[i][k] * m2[k][j];
}
}
return result;
}
K. Lakshmi Narayana 57
KLN Classes and Objects
Multiply matrices using Function return an array
/** Matrix print. */
public static void mprint(int[][] a) First MATRIX
{ int rows = a.length; int cols = a[0].length; array[2][3]
System.out.println("array["+rows+"]["+cols+"]\n"); 3 2 3
for (int i=0; i< rows; i++) 5 9 8
{ for (int j=0; j< cols; j++) Second MATRIX
System.out.print(a[i][j] + "\t"); array[3][2]
System.out.println();
4 7
} 9 3
} 8 1
public static void main(String[] argv){ Resultant MATRIX
int x[][] ={ { 3, 2, 3 }, { 5, 9, 8 } }; array[2][2]
int y[][] ={ { 4, 7 }, { 9, 3 }, { 8, 1 } }; 54 30
165 70
int z[][] = Matrix.multiply(x, y);
System.out.println("\nFirst MATRIX"); Matrix.mprint(x);
System.out.println("\nSecond MATRIX"); Matrix.mprint(y);
System.out.println("\nResultant MATRIX"); Matrix.mprint(z);
}
}
K. Lakshmi Narayana 58
KLN Transpose of a Matrix Classes and Objects

import java.util.*;
class MatrixTranspose
{ int mat[][]; int r,c;
public MatrixTranspose() { }
public MatrixTranspose(int r, int c){ this.r=r; this.c=c; mat=new int[r][c]; }
public void read()
{ int i, j; Scanner sc=new Scanner(System.in);
for(i=0;i<r;i++)
for(j=0;j<c;j++)
mat[i][j]=sc.nextInt();
}
public void display()
{ int i, j;
for(i=0;i<r;i++)
{ for(j=0;j<c;j++)
System.out.print(" "+ mat[i][j]);
System.out.println();
}
}
K. Lakshmi Narayana 59
KLN Classes and Objects
Transpose of a Matrix cont…
public MatrixTranspose transpose(MatrixTranspose m)
{ MatrixTranspose temp=new MatrixTranspose(m.c, m.r); int i, j;
for(i=0; i<m.c; i++)
for(j=0; j<m.r; j++)
temp.mat[i][j] = m.mat[j][i];
return temp;
}
public static void main(String [] args)
{ MatrixTranspose m1=new MatrixTranspose(3, 4);
MatrixTranspose m2;
System.out.println("Enter the elements of 3X4 Matrix"); m1.read();
m2=m1.transpose(m1);
System.out.println("Original Matrix ::"); m1.display();
System.out.println();
System.out.println("Transpose of Matrix ::"); m2.display();
}
K.}Lakshmi Narayana 60
KLN Design a Student class with roll, name, Classes and Objects
5 subjects
import java.util.*;
class Student
{ int roll; String name;
double marks[] = new double[5];
Student(int r, String n)
{ roll=r; name=n;
}
void readMarks()
{ Scanner sc=new Scanner(System.in);
for(int i=0; i<5; i++)
marks[i]=sc.nextInt();
}
void printStudent()
{ System.out.print("Roll " + roll);
System.out.print(", Name " + name);
System.out.println(", Grade :: " + grade());
}
K. Lakshmi Narayana 61
KLN Design a Student class with roll, name, Classes and Objects
5 subjects
String grade()
{ double total=0, avg;
for(int i=0; i<5; i++)
total +=marks[i];
avg=total/5;
if(avg>=60) return "First";
if(avg>=50) return "Second";
if(avg>=40) return "Third";
else return "Fail";
}
public static void main(String ar[])
{ Student s1=new Student(406, "Ram Lal");
System.out.print("Enter 5 Subjects marks :: ");
s1.readMarks();
s1.printStudent();
}
}
K. Lakshmi Narayana 62
KLN Sort Student Objects in ascending orderClasses and Objects
of marks
import java.util.*;
class Student
{ int roll; String name; float marks;
Student(int roll, String name, float marks)
{ this.roll=roll; this.name=name; this.marks=marks;
}
public String toString() //toString method is overloaded
{ return ("Student Roll No :: "+ roll +", Name :: "+ name +", and Marks :: "+ marks + "\n");
}
public static void main(String ar[])
{ int r; String nm; float m; int n;
Scanner key=new Scanner(System.in);
System.out.print("Enter the Number of Students :: ");
n=key.nextInt(); Student s[ ]=new Student[n];
for(int i=0; i<n; i++)
{ System.out.print("Enter the Roll Number :: "); r=key.nextInt();
System.out.print("Enter the Name :: "); nm=key.next();
System.out.print("Enter the Marks :: "); m=key.nextFloat();
s[i]=new Student(r, nm, m);
} Narayana
K. Lakshmi 63
KLN Sort Student Objects in ascending orderClasses and Objects
of marks

//BUBBLE SORT LOGIC


Student temp;
for(int i=0; i<n-1; i++)
{ for(int j=0;j<n-i-1; j++)
{ if(s[j].marks > s[j+1].marks)
{ temp=s[j];
s[j]=s[j+1];
s[j+1]=temp;
}
}
}
System.out.println("\n\nStudent Details in ascending order of Marks::");
for(int i=0; i<n; i++)
System.out.println(s[i]); //OK if you overloaded the toString method
}
} Output in NEXT Page
K. Lakshmi Narayana 64
KLN Classes and Objects
Sort an Array of Objects Cont…

K. Lakshmi Narayana 65
KLN Classes and Objects

Things to Remember
 Top level classes and interfaces must have default or public accessibility.
 transient modifier not applicable to static variables.
 volatile - variable should not be cached by the threads. Threads use local caching
to increase speed. volatile prevents this to support possible loss of integrity.
 for each try block - 0 or more catch block, 0 or 1 finally block, must have at least 1
catch block or 1 finally block.
 Interface methods - public and abstract by default
 Interface constants - public static final by default
 (null instanceof X) always false for any class X.
 explicit calls for gc - System.gc() OR System.runFinalization()
 Class Initialization sequence (1) superclass is initiated
(2) static initialization blocks are executed.
 Object Initialization sequence
(1) Instance variables set to defaults
(2) call chain of constructors
(3) last constructor creates object super object
(4) instance initialization expressions and blocks executed in order of appearance
 static methods can be synchronized
 lock for class static methods is different from lock of object of class.
 Wrapper class Void is not instantiable
K. Lakshmi Narayana 66
66
KLN Classes and Objects

Thank You

K. Lakshmi Narayana

Das könnte Ihnen auch gefallen