Unit 2
Unit 2
.
We can access the members of an object with the help of dot( ) operator.
Example:
//Defining a Student class.
class Student
{
//defining fields
int id; //field or data member or instance variable
String name;
}
//creating main method inside the Student class
class Main
{
public static void main (String args[])
{
//Creating an object or instance
Student s1=new Student(); //creating an object of Student
//Printing values of the object
System.out.println(s1.id); //accessing member through reference variable
System.out.println(s1.name);
}
}
class Student
{
int rollno;
String name;
void insertRecord(int r, String n)
{
rollno=r;
name=n;
}
void displayInformation()
{System.out.println(rollno+" "+name);}
}
class Main{
public static void main(String args[])
{
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
Output
111 Karan
222 Aryan
Stack Memory
The stack memory is a physical space (in RAM) allocated to each thread at run time. It is
created when a thread creates. Memory management in the stack follows LIFO (Last-In-First-
Out) order because it is accessible globally. It stores the variables, references to objects, and
partial results. Memory allocated to stack lives until the function returns. If there is no space
for creating the new objects, it throws the java.lang.StackOverFlowError. The scope of the
elements is limited to their threads. The JVM creates a separate stack for each thread.
Heap Memory
It is created when the JVM starts up and used by the application as long as the application
runs. It stores objects and JRE classes. Whenever we create objects, it occupies space in the
heap memory while the reference of that object creates in the stack. It does not follow any
order like the stack. It dynamically handles the memory blocks. It means, we need not to
handle the memory manually. For managing the memory automatically, Java provides
the garbage collector that deletes the objects which are no longer being used. Memory
allocated to heap lives until any one event, either program terminated or memory free does
not occur. The elements are globally accessible in the application. It is a common memory
space shared with all the threads. If the heap space is full, it throws
the java.lang.OutOfMemoryError. The heap memory is further divided into the following
memory areas:
III. Constructors
Constructors are special member methods of a class which are used to initialise objects when
they are created.
In Java, a constructor is a block of codes similar to the method.
It is called when an instance of the class is created.
At the time of calling constructor, memory for the object is allocated in the memory.
It is a special type of method which is used to initialize the object.
Every time an object is created using the new() keyword, at least one constructor is
called.
It calls a default constructor if there is no constructor available in the class.
Java compiler provides a default constructor by default.
Rules for creating a constructor:
They should have the same name as the class name.
No return type should be specified not even void.
A Java constructor cannot be abstract, static, final, and synchronized.
Constructors Methods
A Constructor is a block of code that A Method is a collection of statements
initializes a newly created object. which returns a value upon its execution.
A Constructor can be used to initialize an A Method consists of Java code to be
object. executed.
A Constructor is invoked implicitly by the A Method is invoked by the programmer.
system.
A Constructor is invoked when a object is A Method is invoked through method calls.
created using the keyword new.
A Constructor doesn’t have a return type. A Method must have a return type.
A Constructor initializes a object that A Method does operations on an already
doesn’t exist. created object.
A Constructor’s name must be same as the A Method’s name can be anything.
name of the class.
A class can have many Constructors but A class can have many methods but must
must not have the same parameters. not have the same parameters.
A Constructor cannot be inherited by A Method can be inherited by subclasses.
subclasses.
In the above example class rectangle, there is a constructor without arguments. The instance
variables length and breadth of the class are assigned the values 5 and 6.
The syntax for creating the objects using constructor without arguments is as follows:
rectangle r = new rectangle ();
The values of length and breadth of the object r are 5 and 6 respectively.
There are many ways to copy the values of one object into another in Java. They are:
• By constructor
• By assigning the values of one object into another
• By clone() method of Object class
By constructor
This involves creating a constructor in the class of the object you want to copy to which takes
an instance of that class as a parameter, and then initializes its own instance variables using
the values from the parameter object.
Output:
111 Karan
111 Karan
Copying values without constructor
We can copy the values of one object into another by assigning the objects values to another
object without the use of a constructor
V. Static Keyword
1) Static variable
The number of copies created for the member data would be equal to the number of
objects of the class type created. Under some conditions, we want one copy of data
irrespective of the number of objects instantiated. Under such conditions you can
create that particular variable as static. One main advantage of declaring a variable
as static is that, It makes your program memory efficient (i.e., it saves memory).
If you declare any variable as static, it is known as a static variable.
The static variable can be used to refer to the common property of all objects
(which is not unique for each object),
Example, the company name of employees, college name of students, etc.
The static variable gets memory only once in the class area at the time of class
loading.
Don’ts
There are two main restrictions for the static method. They are:
1. The static method cannot use non static data member or call non-static method
directly.
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.
They cannot refer to this or super.
Static members can be accessed by non-static member methods.
They can also be called as class methods as they can be invoked with the class
name.
//Java Program to get the cube of a given number using the static method
class Calculate
{
static int cube(int x)
{
return x*x*x;
}
public static void main(String args[])
{
int result=Calculate.cube(5);
System.out.println(result);
}
}
Class Measure
{
int feet; float inches;
void set(int feet,float inches)
{
this.feet =feet;
this.inches = inches
}
void display()
{
System.out.println(this.feet+” “+this.inches);
}
}
Class Measure1
{
Measure m = new Measure();
m.set(6, 7.5f);
m.display()
}
class B{
A4 obj;
B(A4 obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data); //using data member of A4 class
}
}
class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}
Output:10
Class B is the static nested class for the class A. Here members of the outer class A cannot be
accessed by the members of the static nested class B directly. But, the can access the
members of A through its objects.
class OuterClass {
int x = 10;
static class InnerClass {
int y = 5;
}}
public class Main {
public static void main(String[] args) {
OuterClass.InnerClass myInner = new OuterClass.InnerClass();
System.out.println(myInner.y);
}}
Output
5
It is a mechanism in which one object acquires all the properties and behaviors of
a parent object.
It is an important part of OOPs (Object Oriented programming system).
Inheritance in Java is that you can create new classes that are built upon existing
classes.
It inherits from an existing class
It can reuse methods and fields of the parent class.
It can add new methods and fields in the current class also.
Inheritance represents the IS-A relationship which is also known as
a parent-child relationship.
The extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.
In the terminology of Java, a class which is inherited is called a parent or superclass, and the
new class is called child or subclass
Exa
mple:
}
Class Main
{
public static void main(String args[])
{
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
}
}
In this example, Programmer object can access the field of own class as well as of Employee
class i.e. code reusability
Types of inheritance in java Three types of inheritance in java:
1. single,
2. multilevel
3. and hierarchical.
Multilevel Inheritance
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in
the example given below, BabyDog class inherits the Dog class which again inherits the
Animal class, so there is a multilevel inheritance.
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Output:
Hierarchical Inheritance
When two or more classes inherits a single class, it is known as hierarchical inheritance. In
the example given below, Dog and Cat classes inherits the Animal class, so there is
hierarchical inheritance.
X.Java Interface
To access the interface methods, the interface must be "implemented" (kinda like inherited)
by
another class with the implements keyword (instead of extends). The body of the interface
method is provided by the "implement" class.
// Example1 Interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}
// Pig "implements" the Animal interface
class Pig implements Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
public void sleep() {
// The body of sleep() is provided here
System.out.println("Zzz");
}
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
What is Polymorphism?
The derivation of the word Polymorphism is from two different Greek words- poly
and
morphs.
“Poly” means numerous, and “Morphs” means forms.
Polymorphism means innumerable forms.
Polymorphism, is one of the most significant features of Object-Oriented
Programming
Types of Polymorphism
You can perform Polymorphism in Java via two different methods:
1. Method Overloading
2. Method Overriding