Uploaded by keshavmahajan508

Java Unit II Class E Content 23

advertisement
OOP WITH JAVA_UNIT_2_CLASS_E_CONTENT
OBJECT ORIENTED PROGRAMMING WITH JAVA
UNIT-II
Class-Objects-Methods-Overloading methods-Constructors-‘this’ Keyword – Constructor
Overloading - Copy Constructors-Static Data Members-Static Methods-finalize () Methods-Access
Control-Inheritance-Overriding methods-super keyword-Inheritance and Constructors-Abstract
Classes-Final Classes.
2.1 Class
A class is a user defined datatype which contains variables and methods to describe the behavior of an object.
A class is a collection of objects. If a single class is created, then a `n’ number of objects can be created.
The general form of a class is as follows.
class class_name
{
member variables; // class body
methods;
}
Example:
Class Student
{
int m1,m2,m3;
double average()
{
return (m1+m2+m3)/3;
}
}
2.2 Objects
An object is a runtime entity which has a state and behavior. It is an instance of a class which can access the data.
Syntax :
class object_name=new class_name();
Example:
Student student1=new Student();
2.3 Methods
A method is a block of code or collection of statements or a set of code grouped together to perform a certain task or
operation which only runs when it is called.. Methods allow to reuse the code without retyping the code. All variables
declared in method declaration and method parameters are local variables. All methods must define inside a class.
Syntax:
return type method name (arg-list)
{
// body of the method
}
1
OOP WITH JAVA_UNIT_2_CLASS_E_CONTENT
Example:
int total(int m1, int m2, int m3)
{
int tot;
tot= m1+m2+m3;
return tot;
}
2.3.1 Method overloading:
Method Overloading is a feature that allows a class to have more than one method with the same name but with
different parameters. Method overloading is an example of compile time polymorphism.
In the methods, argument can differ in:
1. Number of parameters passed to a method
2. Datatype of parameters
3. Sequence of data types when passed to a method.
Example:
class CalculateSquare
{
public void square()
{
System.out.println("No Parameter Method Called");
}
public int square( int number )
{
int square = number * number;
System.out.println("Method with Integer Argument Called:"+square);
}
public float square( float number )
{
float square = number * number;
System.out.println("Method with float Argument Called:"+square);
}
public static void main(String[] args)
{
CalculateSquare obj = new CalculateSquare();
obj.square();
obj.square(5);
obj.square(2.5);
}
}
2.4 Constructor
A constructor is a special method defined in the class used for object initialization. A constructor is a method in a
class whose name must be same as class name and must not have a return type.
Syntax:
class_name (args)
{
2
OOP WITH JAVA_UNIT_2_CLASS_E_CONTENT
// some initialization statements here
}
Example:
Student ()
{
regNo = 101;
name = “Ahamed”;
}
2.4.1 Default constructor
A constructor without any parameters is called default constructor.
Example:
class Student
{
int regNo;
String name;
Student ()
{
regNo = 101;
name = “Ahamed”;
}
}
2.4.2 Parameterized constructor
A constructor with one or more parameters is called parameterized constructor.
Example:
class Student
{
int regNo;
String name;
Student (int r, String n)
{
regNo = r;
name = n;
}
}
Example Program to initialize student details using default constructor and displaying the same.
class Student
{
int regNo;
String name;
Student ()
{
regNo = 101;
name = “Ahamed”;
}
Student (int r, String n)
{
3
OOP WITH JAVA_UNIT_2_CLASS_E_CONTENT
regNo = r;
name = n;
}
void display ()
{
System.out.println ("Student Roll Number is: " + regNo);
System.out.println ("Student Name is: " + name);
}
}
class ConstructorDemo
{
public static void main(String args[])
{
Student s1 = new Student ();
System.out.println ("s1 object contains:");
s1.display ();
Student s2 = new Student (102, “Mohamed”);
System.out.println ("s2 object contains:");
s2.display ();
}
}
Characteristics of constructors:
A constructor does not return any value, not even void.
A constructor is called and executed at the time of creating an object.
A constructor is called only once per object.
Default constructor is used to initialize every object with same data where as parameterized
constructor is used to initialize each object with different data.
o If no constructor is written in a class then java compiler will provide default values.
o
o
o
o
2.4.3 this keyword
The this keyword refers to the current object in a method or constructor. The most common use of this
keyword is to eliminate the confusion between class attributes and parameters with the same name.
Example:
class Student
{
int regNo;
String name;
Student (int regNo, String name)
{
this.regNo = regNo;
this.name = name;
}
}
2.4.4 Overloading Constructors
In Java, constructors can be overloaded like methods. The constructor overloading can be defined as the
concept of having more than one constructor with different parameters so that every constructor can
perform a different task.
4
OOP WITH JAVA_UNIT_2_CLASS_E_CONTENT
Example1:
class Student
{
int regNo;
String name;
Student ()
{
regNo =101;
name = “Ahamed”;
}
Student (int r, String n)
{
regNo = r;
name = n;
}
void display ()
{
System.out.println ("Student Roll Number is: " + regNo);
System.out.println ("Student Name is: " + name);
}
}
class ConstructorOverload
{
public static void main(String args[])
{
Student s1 = new Student ();
System.out.println ("s1 object contains:");
s1.display ();
Student s2 = new Student (102, “Mohamed”);
System.out.println ("s2 object contains:");
s2.display ();
}
}
Example2:
class Area
{
int length, breadth;
Area(int i)
{
length = breadth = i;
}
Area(int i, int j)
{
length = i;
breadth = j;
}
int area()
{
return length * breadth;
}
}
5
OOP WITH JAVA_UNIT_2_CLASS_E_CONTENT
class OverCons
{
public static void main(String args[])
{
Area A = new Area (10,5);
Area A1 = new Area (5);
System.out.println (“The area of square is :” +A. area());
System.out.println (“The area of rectangle is :” +A1.area());
}
}
Here when the object A is initialized, the constructor with two parameters is used and for initializing object A1, the
constructor with a single parameter is used.
2.4.5 Copy Constructors:
Copy Constructor is a constructor used to create a copy of a previously existing object present in the class. It is a
special type of constructor that returns a duplicate copy of another object.
Example:
class Student
{
int regNo;
String name;
Student (int r, String n)
{
regNo = r;
name = n;
}
Student(Student obj)
{
regNo= obj.regNo;
name=obj.name;
}
void display ()
{
System.out.println ("Student Roll Number is: " + regNo);
System.out.println ("Student Name is: " + name);
}
}
class CopyConstructor
{
public static void main(String args[])
{
Student s1 = new Student(101,"Ahmed");
s1.display ();
Student s2 = new Student (s1);
s2.display ();
}
}
6
OOP WITH JAVA_UNIT_2_CLASS_E_CONTENT
Output:
Student Roll Number is: 101
Student Name is: Ahmed
Student Roll Number is: 101
Student Name is: Ahmed
2.5 Static Data members
Static data members are those whose memory space is created only once, whenever the class is loaded in the main
memory irrespective of no of objects are created.
Static data members are meant for storing common values and it is shared by all the instances of the class.
Programmatically static data member declaration must be preceded by static keyword.
Syntax:
Example:
static data type v1, v2, v3 ………. Vn;
static int a;
Each and every static data member must be accessed with the respective class name and doesn’t need any object.
Syntax:
classname.staticdatamember_name;
Example 1:
class StaticData
{
static int s;
public static void main(String args[])
{
System.out.println(StaticData.s);
}
}
Example 2:
class Student
{
int rollno;
String name;
static String subject ="Java";
Student(int r, String n)
{
rollno = r;
name = n;
}
void display ()
{
System.out.println(rollno+" "+name+" "+college);}
}
}
public class StaticDataMember
{
public static void main(String args[])
{
Student s1 = new Student(111,"Ahamed");
7
OOP WITH JAVA_UNIT_2_CLASS_E_CONTENT
Student s2 = new Student(222,"Abdul");
//The subject of all objects can be changed by the single line of code
//Student.subject="OS";
s1.display();
s2.display();
}
}
2.5.1 Static methods
It is a method which belongs to the class and not to the object. A static method shall be declared using the static
keyword.
Syntax:
static returntype methodname(args)
{
}
Characteristics of Static Methods

A static method can access only static data. It cannot access non-static data (instance variables).

A static method can call only other static methods and cannot call a non-static method from it.

A static method can be accessed directly by the class name and doesn’t need any object.
o Syntax: <class-name>.<static method-name>

A static method cannot refer to “this” or “super” keywords in anyway.
Example:
class Student
{
int rollno;
String name;
static String subject ="Java";
Student(int r, String n)
{
rollno = r;
name = n;
}
static void changeSubject( )
{
subject="OS";
}
void display ()
{
System.out.println(rollno+" "+name+" "+subject);
}
}
public class StaticMethod
{
public static void main(String args[])
{
Student s1 = new Student(111,"Ahamed");
s1.display();
8
OOP WITH JAVA_UNIT_2_CLASS_E_CONTENT
Student s2 = new Student(222,"Abdul");
Student.changeSubject( );
s2.display();
}
}
Output:
111 Ahamed Java
222 Abdul OS
2.6 finalize ( ) method:
finalize ( ) method is a method of Object class which is called just before the destruction of an object by the
garbage collector. The purpose of calling finalize method is to perform cleanup activities like closing the resources
like database connection, network connection, etc.
The finalize( ) method has this general form:
protected void finalize( )
{
finalization code here
}
2.7 Access Control
Access Control is used to restrict the access to certain variables and methods from outside the class. Java has the
four levels of access modifiers. They are private, public, protected and default.
(i) private: It is accessible only by methods of this class.
Example: private int k;
private void add()
Example Program:
class Private
{
private String name;
private void display()
{
System.out.println(name);
}
}
class PrivateDemo
{
public static void main(String[] main)
{
Private d = new Private();
d.name = "The New College";
d.display();
}
}
Output:
PrivateDemo.java:18: error: name has private access in Data
9
OOP WITH JAVA_UNIT_2_CLASS_E_CONTENT
d.name = "The New College";
^
(ii) public: It is accessible by methods of all classes.
Example: public double NetSalary()
public String read()
Example Program:
class Public
{
public String name;
public void display()
{
System.out.println(name);
}
}
class PublicDemo
{
public static void main(String[] main)
{
Public d = new Public();
d.name = "The New College";
d.display();
}
}
Output:
The New College
(iii) protected: It is accessible to classes with in the package and the subclasses of other package.
Example: protected int regno;
protected double avg()
Example Program:
package A;
public class Protected
{
protected String name;
protected void display()
{
System.out.println(name);
}
}
package B;
import A.*;
class ProtectedDemo extends Protected
{
public static void main(String[] main)
{
ProtectedDemo d = new ProtectedDemo();
10
OOP WITH JAVA_UNIT_2_CLASS_E_CONTENT
d.name = "The New College";
d.display();
}
}
Output:
The New College
(iv) default (declared/defined without using any modifier) : It is accessible within the same class and package
within which its class is defined.
Example: int regno;
double avg()
Example Program:
package A;
public class Default
{
String name;
void display()
{
System.out.println(name);
}
}
package A;
public class DefaultDemo1 extends Default
{
public static void main(String[] main)
{
Default d = new Default();
d.name = "The New College";
d.display();
}
}
Output:
The New College
Access Location
Same Class
Sub Class in Same Package
Other Class in Same Package
Sub Classes in Other Packages
Non Sub Classes in Other Packages
public
Yes
Yes
Yes
Yes
Yes
protected
Yes
Yes
Yes
Yes
No
Table 2.1 Access Control
Package/default private
Yes
Yes
Yes
Yes
No
No
No
No
No
No
2.8 Inheritance
The mechanism of deriving a new class from an old one is called inheritance. The old class is known as base class
or super class or parent class and the new one is called the sub class or child class.
The inheritance allows subclasses to inherit all variables and methods of their parent classes.
11
OOP WITH JAVA_UNIT_2_CLASS_E_CONTENT
2.8.1 Defining a subclass
A class that is derived from another class is called a subclass (also a derived class, extended class, or child class).
The class from which the subclass is derived is called a superclass (also a base class or a parent class).
A subclass is defined as follows
class subclassname extends superclassname
{
variables declaration;
method declaration;
}
The keyword extends signifies that the properties of the superclassname are extended to the subclassname.
Example Program:
class Parent
{
void display1()
{
System.out.println(“This is the parent Class”);
}
}
class Child extends Parent
{
void display2()
{
System.out.println(“This is the Child Class”);
}
}
class SingleInheritance
{
public static void main(String args[])
{
Child c=new Child();
c.display1();
c.display2();
}
}
2.8.2 Types of inheritance in java
On the basis of class, there can be 3 types of inheritance in java: single, multilevel and hierarchical. In java
programming, multiple and hybrid inheritance is supported through interface only.
Single Inheritance:
In a class hierarchy when a child has one and only one parent and parent has one only child, that inheritance is said
to be single inheritance.
Multi-level Inheritance:
In a class hierarchy, when a class is derived from already derived class then that inheritance is said to be multilevel inheritance.
12
OOP WITH JAVA_UNIT_2_CLASS_E_CONTENT
Hierarchical inheritance:
In a class hierarchy, when a parent class has two or more than two child classes then, the inheritance is said to be
hierarchical inheritance.
Example Program:
class Parent
{
void display1()
{
System.out.println(“This is the parent Class”);
}
}
class Child1 extends Parent
{
void display2()
{
System.out.println(“This is the Child1 Class”);
}
}
class Child2 extends Parent
{
void display2()
{
System.out.println(“This is the Child2 Class”);
}
}
class HierarchicalInheritance
{
public static void main(String args[])
{
Child1 c=new Child1();
System.out.println(“Inheriting Parent class using Child1”);
c.display1();
c.display2();
Child2 c1=new Child2();
System.out.println(“Inheriting Parent class using Child2”);
c1.display1();
c1.display2();
}
}
2.8.3 Method overriding:
A method in a subclass has the same name, type of the variable and order of the variables as a method in its super
class, then the method in the sub class is said to be override the method in the super class. This process is called
method overriding.
Example:
class Animal
{
13
OOP WITH JAVA_UNIT_2_CLASS_E_CONTENT
void move()
{
System.out.println ("Animals can move");
}
}
class Dog extends Animal
{
void move()
{
System.out.println ("Dogs can walk and run");
}
}
public class OverRide
{
public static void main(String args[])
{
Animal a = new Animal ();
Animal b = new Dog ();
a.move ();// runs the method in Animal class
b.move ();// runs the method in Dog class
}
}
2.8.4 Inheritance and Constructors
super keyword
The super keyword in java is a reference variable that is used to refer immediate parent class object. Whenever an
instance of subclass is created, an instance of parent class is created implicitly i.e. referred by super reference
variable.
Usage of java super Keyword
1) super is used to refer immediate parent class instance variable.
2) super() is used to invoke immediate parent class constructor.
3) super is used to invoke immediate parent class method.
class Super
{
int i;
Super()
{
i=1;
System.out.println("In Super Class Constructor");
}
void display()
{
System.out.println("This is the display() method of Super Class");
}
}
class Sub extends Super
{
int i;
14
OOP WITH JAVA_UNIT_2_CLASS_E_CONTENT
Sub()
{
i=2;
System.out.println("In Sub Class Constructor");
}
void display()
{
System.out.println("Displaying Super Variable:"+super.i);
System.out.println("Displaying Sub Variable:"+i);
super.display();
System.out.println("This is the display() method of Sub Class");
}
}
class SuperDemo
{
public static void main(String args[])
{
Sub d=new Sub();
d.display();
}
}
Output:
In Super Class Constructor
In Sub Class Constructor
Displaying Super Variable:1
Displaying Sub Variable:2
This is the display() method of Super Class
This is the display() method of Sub Class
2.9 Abstract Class:
An abstract class is a class which is declared using abstract keyword. Abstract classes are very similar as normal
classes except that they can have abstract methods as well along with concrete methods. No instance can be
created of an abstract class, because simply it is designed to be act as a base class.
Syntax:
abstract class classname
{
abstract method();
}
Example Program:
import java.io.*;
abstract class A
{
abstract void callme();
void callmetoo()
{
System.out.println("This is a concrete method");
}
}
class B extends A
15
OOP WITH JAVA_UNIT_2_CLASS_E_CONTENT
{
void callme()
{
System.out.println("B’s implementation of abstract method callme.");
}
}
class AbstractDemo
{
public static void main(String args[])
{
B b= new B();
b.callme();
b.callmetoo();
}
}
2.10 Final Classes
A final class is a class that can't be extended. Also methods could be declared as final to indicate that cannot be
overridden by subclasses. Preventing the class from being sub classed could be particularly useful if it is to write
APIs or libraries and want to avoid being extended to alter base behaviour.
Syntax:
final class classname
{
//final class variables and methods
}
Example Program:
final class C
{
void display1()
{
System.out.println(“This is the Final Class”);
}
}
class D extends C
{
void display2()
{
System.out.println(“This is Class D”);
}
}
class FinalDemo
{
public static void main(String args[])
{
C obj=new C();
System.out.println(“Calling display1 method using Final class C”);
obj.display1();
D obj1=new D();
16
OOP WITH JAVA_UNIT_2_CLASS_E_CONTENT
System.out.println(“Calling display1 method using class D”);
obj1.display1();
obj1.display2();
}
}
When compiling this program, the compiler will throw an error that the Class A is final and it cannot be extended.
17
Download