Sybcs Java Unit-3
Sybcs Java Unit-3
R
UNIT-III Classes, Objects and In Java variables or data members are called
fields and functions are called methods.
Methods Class creates objects and objects used methods
Introduction: Object is the physical as well as
to access data members.
logical entity where as class is the only logical
The keyword “class” is used to define a class. A
entity.
class is a user defined data type. Following is the
Class: Class is a blue print which is containing syntax of defining a class.
only list of variables and method and no memory is Syntax:
allocated for them. A class is a group of objects that
has common properties.
A class in java contains:
1. Data Member
2. Method
3. Constructor
4. Block
5. Class and Interface
Object: Object is a instance of class, object has
state and behaviors.
An Object in java has three characteristics: There is no semicolon at the end of the class.
State The definition of class creates only the new abstract
Behavior datatype.
Identity <ClassName> and <SuperClassName> are any
State: Represents data (value) of an object. valid java identifier. The keyword extends indicates
Behavior: Represents the behavior that the properties of the super class are extended to
(functionality) of an object such as deposit, the current class.
withdraw etc. E.g.
Identity: Object identity is typically
implemented via a unique ID. The value of the ID is
not visible to the external user. But, it is used
internally by the JVM to identify each object
uniquely.
Class is also can be used to achieve user defined
data types.
In real world many examples of object and class
like dog, cat, and cow are belong to animal’s class.
Each object has state and behaviors. For example a
dog has state – color, name, height, age as well as
behaviors – barking, eating, and sleeping.
1. Defining a class
Java is a true object oriented programming
language therefore each variable and method must be
defined within a class. Methods and variables inside
the class are known as members.
-1-
Core Java By Kadam R.R
The class body must contain one or more
methods.
2. Creating objects
Once a class has been defined we can
create variables of that type known as objects. In
Java objects are created by using new operator.
The new operator allocates the memory at
runtime and support the dynamic nature of Java.
The following is the syntax of creating an object.
The variables inside the class are known as
instance variables because they are created whenever
an object of the class is instantiated. There is no
storage space is created for class in the memory.
Methods/functions Declaration
A class only data fields has no life. The objects
created by such a class can not respond to messages. Syntax:
We must therefore add methods that are necessary for
manipulating the data contained in the class. To E.g.
accessthe instance variables we have to include
methods in the class.
The general form of a method declaration is:
Advantages of constructors:
A constructor eliminates placing the default
values.
A constructor eliminates calling the normal or
ordinary method implicitly.
Rules or properties of a constructor
Constructor will be called automatically when Method Constructor
the object is created. 1 Method can be any user Constructor must be
Constructor name must be similar to name of defined name class name
the class. 2 Method should have It should not have any
Constructor should not return any value even return type return type (even void)
void also. Because basic aim is to place the 3 Method should be It will be called
value in the object. (if we write the return type called explicitly either automatically whenever
for the constructor then that constructor will with object reference object is created
be treated as ordinary method). or class reference
Constructor definitions should not be static. 1 Method is not provided The java compiler
Because constructors will be called each and by compiler in any case. provides a default
every time, whenever an object is creating. constructor if we do not
Constructor should not be private provided an have any constructor.
object of one class is created in another class
(Constructor can be private provided an 7. Types of constructors
object of one class created in the same class). Based on creating objects in Java constructor are
Constructors will not be inherited from one classified in two types. They are
class to another class (Because every class I. Default or no argument Constructor
constructor is create for initializing its own II. Parameterized constructor.
data members). Default Constructor
The access specifier of the constructor may or A constructor is said to be default constructor
may not be private. if and only if it never take any parameters.
1. If the access specifier of the constructor is If any class does not contain at least one user
defined constructor than the system will create a
private then an object of corresponding class
default constructor at the time of compilation it is
can be created in the context of the same class
known as system defined default constructor.
but not in the context of some other classes.
Syntax:
2. If the access specifier of the constructor is not
private then an object of corresponding class
can be created both in the same class context
and in other class context.
-7-
Core Java By Kadam R.R
Purpose of default constructor?
Default constructor provides the default
values to the object like 0, 0.0, null etc. depending
on their type (for integer 0, for string null).
class Student
{
int roll;
float marks;
String name;
void show()
{
[Link]("Roll: "+roll);
[Link]("Marks: "+marks);
[Link]("Name: "+name);
}
}
class TestDemo
Note: System defined default constructor is {
created by java compiler and does not have any public static void main(String [] args)
statement in the body part. This constructor will be {
executed every time whenever an object is created Student s1=new Student();
if that class does not contain any user defined [Link]();
constructor. }
Example of default constructor. }
In below example, we are creating the no Output
argument constructor in the Test class. It will be Roll: 0
invoked at the time of object creation. Marks: 0.0
Example Name: null
//[Link] Explanation: In the above class, we are not
class Test creating any constructor so compiler provides a
{ default constructor. Here 0, 0.0 and null values are
int a, b; provided by default constructor.
Test ()
{
[Link]("I am from default Constructor...");
a=10; Parameterized constructor
b=20; Def1: If any constructor contain list of variable in
[Link]("Value of a: "+a); its signature is known as paremetrized constructor.
[Link]("Value of b: "+b); Def2: A constructor that have parameters is known
} as parameterized constructor.
}; A parameterized constructor is one which
class TestDemo takes some parameters.
{ Why use parameterized constructor?
public static void main(String [] args) Parameterized constructor is used to provide
{ different values to the distinct objects.
Test t1=new Test (); Syntax:
}
};
Output
Output:
I am from default Constructor...
Value of a: 10
Value of b: 20
-8-
Core Java By Kadam R.R
constructor and default constructor, It must be
define both the constructors.
In any class maximum one default constructor
but 'n' number of parameterized constructors.
8. 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 the number of parameters, and their type.
In other words whenever same constructor is
existing multiple times in the same class with different
number of parameters or order of parameters or type
of parameters is known as Constructor overloading.
In general constructor overloading can be used
Syntax to call parametrized constructor to initialized same or different objects with different
values.
Syntax
class Test
{
int a, b;
Test(int n1, int n2)
{
[Link]("I am from Parameterized
Constructor...");
a=n1;
b=n2;
[Link]("Value of a = "+a);
[Link]("Value of b = "+b);
}
};
class TestDemo1
{
public static void main(String k [])
{
Test t1=new Test(10, 20); Why overriding is not possible at constructor level.
} The scope of constructor is within the class so
}; that it is not possible to achieved overriding at
constructor level.
Important points Related to Parameterized
Constructor 9. Static Fields/variables and methods
Whenever we create an object using Static Fields/variables
parameterized constructor, it must be define The static keyword is used in java mainly for
parameterized constructor otherwise we will memory management. Static keyword are used with
get compile time error. Whenever we define the variables, methods. If you declare any variable as
objects with respect to both parameterized static, it is known static variable.
-9-
Core Java By Kadam R.R
If the value of a variable is not varied from Student1 s1=new Student1(101,"Karan");
object to object we should declare those variables at Student1 s2=new Student1(102,"Arjun");
the class level by using static modifier. [Link]();
In the case of instance variables for every [Link]();
object a separate copy will be created but in the case of }
static variables at the class level a single copy will be }
created and shared that copy by all objects of that O/P
class. 101 Karan MGM
Static variables can be created at the time of 102 Arjun MGM
class loading and destroyed at the time of class Non-static variable Static variable
unloading hence the scope of static variables is exactly
same as the scope of .class file. 1 These variable
We can access static variables either by using should not be These variables are
object reference or by using class name but usage of preceded by any preceded by static
class name is recommended. static keyword keyword. Example:
Within the same class it is not required to use Example: class A
class name also we can access static variables directly. class A {
When and why we use static variable { static int b;
Suppose we want to store record of all int a; }
employee of any company, in this case employee id }
is unique for every employee but company name is
common for all. 2 Memory is allocated
Memory is allocated for
When we create a static variable as a for these variable
these variable at the time
company name then only once memory is allocated whenever an object is
of loading of the class.
otherwise it allocates a memory space each time for created
every employee. The following is the syntax of
3 Memory is allocated
declaring static variables. Memory is allocated for
multiple time
Syntax: these variable only once
whenever a new
in the program.
object is created.
4 Non-static variable
E.g
also known as Memory is allocated at
instance variable the time of loading of
while because class so that these are
memory is allocated also known as class
The following example shows the use of static
whenever instance is variable.
variables:
created.
class Student1
{ 5 Non-static variable Static variable are
int seatNo; are specific to an common for every object
String name; object that means there memory
static String collegeName="MGM"; location can be sharable
Student1(int seatNo, String name) by every object reference
{ or same class.
[Link]=seatNo;
[Link]=name; 6 Non-static variable
Static variable can access
} can access with
with class reference.
void display() object reference.
Syntax:
{ Syntax
class_name.variable_name
[Link](seatNo+" "+name+" obj_ref.variable_name
"+collegeName);
} 10. Static Methods
public static void main(String[] args) If you apply static keyword with any method,
{ it is known as static method.
- 10 -
Core Java By Kadam R.R
In case of non static method memory is Student2 s3 = new Student2 (333,"Devilal");
allocated multiple times whenever method is [Link]();
calling. But in case of static method memory is [Link]();
allocated only once at the time of class loading. [Link]();
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. O/P
Syntax for declare static method: 111 Karan MGM
222 Arjun MGM
333 Devilal MGM
2. Multiple inheritance
The mechanism of inheriting the
features of more than one base class into a
single class is known as multiple
inheritance.
Java doesn’t support multiple
inheritance through classes but it can be Fig. Hierarchical Inheritance
achieved by using the interfaces. Syntax:
E.g.
E.g.
- 14 -
Core Java By Kadam R.R
class Test
{
public static void main(String[] args)
{
B b1=new B();
C b2=new C();
D b3=new D();
[Link]();
[Link]();
[Link]();
}
}
O/P
javac [Link]
java Test
In showB()
a=10
1. W.a.p to demonstrate the hierarchical b=20
inheritance. In showC()
class A a=10
{ b=30
int a=10; In showD()
} a=10
class B extends A b=40
{
int b=20;
void showB()
{ class Faculty
[Link]("In showB()"); {
[Link]("a="+a); float salary=50000.00f;
[Link]("b="+b); }
} class Science extends Faculty
} {
class C extends A float bonus=20000.00f;
{ void displaySalary()
int c=30; {
void showC() [Link]("Faculty : Science");
{ [Link]("Salary: "+salary);
[Link]("In showC()"); [Link]("Bonus: "+bonus);
[Link]("a="+a); }
[Link]("b="+c); }
} class Commerce extends Faculty
} {
class D extends A float bonus=15000.00f;
{ void displaySalary()
int d=40; {
void showD() [Link]("Faculty : Commerce");
{ [Link]("Salary: "+salary);
[Link]("In showD()"); [Link]("Bonus: "+bonus);
[Link]("a="+a); }
[Link]("b="+d); }
} class Art extends Faculty
} {
float bonus=10000.00f;
- 15 -
Core Java By Kadam R.R
void displaySalary()
{
[Link]("Faculty : Art");
[Link]("Salary: "+salary);
[Link]("Bonus: "+bonus);
}
}
class SalaryDetails
{
public static void main(String[] args)
{
Science s=new Science();
Commerce c=new Commerce();
Art a=new Art();
[Link]();
[Link]();
[Link]();
}}
javac [Link]
java SalaryDetails
O/P Fig. Multilevel Inheritance
Faculty : Science When a sub-class is derived from a derived
Salary: 50000.0 class then this mechanism is called as multilevel
Bonus: 20000.0 inheritance. Multilevel inheritance can go up to
Faculty : Commerce any number of levels.
Salary: 50000.0 E.g.
Bonus: 15000.0
Faculty : Art
Salary: 50000.0
Bonus: 10000.0
4. Multilevel inheritance
In Multilevel inheritances there exists single
base class, single derived class and multiple
intermediate base classes.
Single base class + single derived class +
multiple intermediate base classes.
- 16 -
Core Java By Kadam R.R
[Link]("a="+a); public void showStudent()
[Link]("b="+b); {
} [Link]("Roll No : "+rollNo);
} [Link]("Name : "+name);
class C extends B }
{ }
int c=30; class Marks extends Student
void showC() {
{ int s1,s2,s3,s4;
[Link]("In showC()"); public void setMarks(int s1, int s2, int s3, int s4)
[Link]("a="+a); {
[Link]("c="+c); this.s1=s1;
} this.s2=s2;
} this.s3=s3;
class D extends C this.s4=s4;
{ }
int d=40; public void showMarks()
void showD() {
{ [Link]("S1 : "+s1);
[Link]("In showD()"); [Link]("S2 : "+s2);
[Link]("a="+a); [Link]("S3 : "+s3);
[Link]("d="+d); [Link]("S4 : "+s4);
} }
public static void main(String[] args) }
{ class Result extends Marks
D d1=new D(); {
[Link](); int total;
[Link](); float percentage;
[Link](); public void calculate()
} {
} total=s1+s2+s3+s4;
javac [Link] percentage=total/4;
java D }
O/P public void showResult()
In showB() {
a=10 [Link]("Total Marks : "+total);
b=20 [Link]("Percentage : "+percentage);
In showC() }
a=10 public static void main(String[] args)
c=30 {
In showD() Result r=new Result();
a=10 [Link](101,"Raj");
d=40 [Link]();
2. The following program demonstrates the [Link](50,40,65,36);
multilevel inheritance: [Link]();
class Student [Link]();
{ [Link]();
int rollNo; }
String name; }
void setStudent(int rollNo, String name) javac [Link]
{ java Result
[Link]=rollNo; O/P
[Link]=name; Roll No : 101
} Name : Raj
- 17 -
Core Java By Kadam R.R
S1 : 50 collecting un-used memory space and improved
S2 : 40 the performance of java application.
S3 : 65
S4 : 36
Total Marks : 191 Super Keyword
Percentage : 47.0 Super keyword in java is a reference variable
that is used to refer parent class object. Super is an
implicit keyword creates by JVM and supply each and
every java program for performing important role in
Important Points for Inheritance: three places.
1. In java programming one derived class can 1. Accessing Super class variables
extends only one base class because java 2. Accessing Super classmethods
programming does not support multiple 3. Accessing Super classconstructor
inheritance through the concept of classes, but
it can be supported through the concept of Need of super keyword:
Interface. Whenever the derived class is inherits the
2. Whenever we develop any inheritance base class features, there is a possibility that base
application first create an object of bottom class features are similar to derived class features
most derived class but not for top most base and JVM gets an ambiguity. In order to
class. differentiate between base class features and
3. When we create an object of bottom most derived class features must be preceded by super
derived class, first we get the memory space for keyword.
the data members of top most base class, and Syntax
then we get the memory space for data [Link]
member of other bottom most derived class.
4. Bottom most derived class contains logical 1. Accessing Super class variables
appearance for the data members of all top Whenever the derived class inherits base class
most base classes. data members there is a possibility that base class data
5. If we do not want to give the features of base member are similar to derived class data member and
class to the derived class then the definition of JVM gets an ambiguity.
the base class must be preceded by final hence In order to differentiate between the data
final base classes are not reusable or not member of base class and derived class, in the context
inheritable. of derived class the base class data members must be
6. If we are do not want to give some of the preceded by super keyword.
features of base class to derived class than such Syntax
features of base class must be as private hence super.superclass_datamember_name
private features of base class are not If we are not writing super keyword before the
inheritable or accessible in derived class. base class data member name than it will be referred
7. Data members and methods of a base class can as current class data member name and base class data
be inherited into the derived class but member are hidden in the context of derived class.
constructors of base class can not be inherited The following example demonstrate the use of
because every constructor of a class is made for super keyword for accessing super class variables.
initializing its own data members but not made class Employee
for initializing the data members of other {
classes. float salary=10000;
An object of base class can contain details }
about features of same class but an object of class HR extends Employee
base class never contains the details about {
special features of its derived class (this concept float salary=20000;
is known as scope of base class object). void display()
For each and every class in java there exists {
an implicit predefined super class called [Link]("Base class Salary: "+[Link]);
[Link]. because it providers garbage [Link]("Child class Salary: "+salary);
collection facilities to its sub classes for }
- 18 -
Core Java By Kadam R.R
} In case there is no method in subclass as
class Supervarible parent, there is no need to use super.
{
public static void main(String[] args) 3. Accessing Super class constructor
{ The super keyword can also be used to
HR obj=new HR(); invoke or call the parent class constructor.
[Link](); Constructor are calling from bottom to top and
} executing from top to bottom.
} To establish the connection between base
javac [Link] class constructor and derived class constructors
java Supervarible JVM provides two implicit methods they are:
O/P 1. super()
Base class Salary: 10000.0 2. super(parameterList)
Child class Salary: 20000.0
1. super()
2. Accessing Super class methods It is used for calling super class default
The super keyword can also be used to invoke constructor from the derived class constructors.
or call parent class method. It should be use in case of The following example demonstrate how to call
method overriding. super class constructor from sub-class constructor:
In other word super keyword use when base class Vehicle
class method name and derived class method name {
have same name. Vehicle()
The following example demonstrate the use {
of super keyword for accessing super class [Link]("Vehicle is created");
method. }
class Parent }
{ class Bike extends Vehicle
int bikeSpeed=50; {
public void showSpeed() Bike()
{ {
[Link]("Parent's speed : "+bikeSpeed); super();//will invoke parent class constructor
} [Link]("Bike is created");
} }
class Child extends Parent public static void main(String args[])
{ {
int speed=100; Bike b=new Bike();
public void showSpeed() }
{ }
[Link]("Child's speed : "+speed); javac [Link]
[Link](); java Bike
} O/P
public static void main(String[] args) Vehicle is created
{ Bike is created
Child c1=new Child(); The first line inside constructor should be
[Link](); either super() or this().
} If we are not writing then compiler will always
} generate super keyword.
javac [Link]
java Child
O/P
Child's speed : 100
Parent's speed : 50
- 19 -
Core Java By Kadam R.R
subclass need to modify the implementation (code)
of a method defined in the superclass without
changing the parameter list. This is achieved by
overriding or redefining the method in the subclass.
If sub class has the same method as
declared in the parent class, it is known as “method
overrding”.
In other words, if the sub-class provides
specific implementation of the method that has
We can use super() only at the first line of been provided by one of its parent class, it is known
constructor, if we are using anywhere else we will as “method overriding”.
get CE: If we doesn’t satisfy with the parent class
call to super must be first statement in implementation then we should override that
constructor. method in the sub-class in our own way.
E.g.
- 21 -
Core Java By Kadam R.R
E.g.
- 22 -
Core Java By Kadam R.R
void speed()
{
[Link]("Speed limit is 50 km/hr..");
}
}
class Car extends Vehicle
{
void speed()
{
[Link]("Speed limit is 80 km/hr..");
}
}
class AbsTest
{
public static void main(String args[])
{
Bike b = new Bike();
Car c=new Car();
[Link]();
[Link]();
}
}
javac [Link]
java AbsTest
O/P
Speed limit is 50 km/hr..
Speed limit is 80 km/hr..
- 23 -