SlideShare a Scribd company logo
By- Shalabh Chaudhary [GLAU]
OOPs + INHERITANCE
OOP  Object Oriented Programming is a programming paradigm which
uses "Objects" consisting of data fields and methods together with their
interactions.
Classes and Objects 
 A class contains variable declarations and method definitions.
 Variable declared inside method – Local Variable.
 Variable declared inside class & outside method – Instance Variable.
 Variables with method declarations - parameters or arguments. Mthd(int var/arg){}.
 Class Variable – Can be static.
 Local Variable – Can’t be static.
Objects and References 
 All other types, except 8 primitive data type, refers to objects.
 Variables that refers to objects are reference variables.
 Once class is defined, you can declare a variable(object reference) of type class.
Student stud1;
Employee emp1;
NOTE: Both stud1 and emp1 are objects or reference var but not object of
Student/Employee class, it only holds reference of new object created.
 The new operator is used to create an object of that reference type
Employee emp = new Employee(); // Employee() – object.
 Object references are used to store objects.
 The new operator,
 Dynamically allocates memory for an object
 Creates the object on the heap
 Returns a reference to it - The reference is then stored in the variable.
Constructors 
Constructor is automatically invoked whenever an object of the class is created.
Used to initialize instance variables.
 Rules to Define Constructor -
 A constructor has the same name as the class name.
 Should not have a return type.
 Can be defined with any access specifier (like private, public).
 A class can contain more than one constructor, So it can be overloaded.
By- Shalabh Chaudhary [GLAU]
 Eg.:
public class Sample {
private int id;
Sample() {
id = 101;
System.out.println("Default constructor,with ID: "+id);
}
Sample(int no){
id = no;
System.out.println("One arg constructor,withID: "+ id);
}
}
public class ConstDemo{
public static void main(String[] args) {
Sample s1 = new Sample();
Sample s2 = new Sample(102);
}
}
Output - Default constructor,with ID: 101
One argument constructor,with ID: 102
this reference keyword 
Each class member funct contains an implicit reference of its class type, named this.
 this reference is created automatically by compiler.
 It contains the address of the object through which the function is invoked.
 Use of this keyword.
 To refer instance var when there is clash with local var or method arguments.
 Used to call overloaded constructors from another constructor of same class.
 Use this.variableName to explicitly refer to instance variable.
 The this reference is implicitly used to refer to instance variables and methods.
 It CANNOT be used in a static method.
 Ex1: void setId(intid) {
this.id = id;
}
 Ex2: class Sample{
Sample(){
this("Java"); // calls overloaded constructor
System.out.println("Default constructor ");
}
Sample(String str){
System.out.println("One argument constructor "+ str);
}
}
By- Shalabh Chaudhary [GLAU]
Static Class Members
Static class members are members of class that don’t belong to instance of a class.
 We can access static members directly by prefixing the members with class name
ClassName.staticVariable
ClassName.staticMethod(...)
Static variables:
 Shared among all objects of the class.
 Only one copy exists for the entire class to use.
Static methods :
 Static methods can only access directly the static members and manipulate a
class’s static variables.
 Static methods cannot access non-static members(instance variables or
instance methods) of the class.
 Static method can’t access this and super references.
 Eg.:
class StaticDemo {
private static inta = 0;
private int b;
public void set ( int i, int j) {
a = i; b = j;
}
public void show() {
System.out.println("This is static a: " + a );
System.out.println( "This is non-static b: " + b );
}
public static void main(String args[]) {
StaticDemox = new StaticDemo();
StaticDemoy = new StaticDemo();
x.set(1,1);
x.show();
y.set(2,2);
y.sow();
x.show();
}
}
Output: This is static a: 1
This is non-static b: 1
This is static a: 2
This is non-static b: 2
This is static a: 2
This is non-static b: 1
QQ. Why is main() method static ?
By- Shalabh Chaudhary [GLAU]
OUTPUT BASED 
 class Sample{
int i_val;
public static void main(String[] xyz){
System.out.println("i_val is :"+ this.i_val);
}
}
>> Error: non-static variable this cannot be referenced from a static context
 class Sample {
int i_val=10;
Sample(int i_val){
this.i_val=i_val;
System.out.println("inside Sample i_val: "+this.i_val);
}
public static void main(String[] xyz){
Sample o = new Sample();
}
}
>> Error: No default constructor created.
“static” Block 
A block of code enclosed in braces, preceded by the keyword static.
Eg.:
static {
System.out.println(“Within static block”);
}
 The statements within the static block are executed automatically when the class is
loaded into JVM.
 They are executed in the order of their appearance in the class.
 JVM combines all static blocks in a class as single static block and executes them.
 class Sample{
public static void main(String[] xyz){
System.out.println("Inside main method line1");
}
static {
System.out.println("Inside class line1");
}
}
>> Inside class line1
Inside main method line1
By- Shalabh Chaudhary [GLAU]
***Create object of First class in Second class using new opr & run Second class print
something.
 public class DefaultConstruct {
String name;
int roll;
void detail() {
System.out.println(name); // initialize null by default.
System.out.println(roll); // initialize to 0 by default.
}
public static void main(String[] args) {
DefaultConstruct d = new DefaultConstruct();
d.detail();
}
}
// >> constructor not defined then default constructor is created.
// >> Default constructor has no parameter it initializes instance var
to default values.
// >> // Can Define Constructor like –
DefaultConstruct (){ initialize values; }
Constructor v/s Method 
 Doesn’t have return type but Method has return type.
 Called using new operator & Method called using (.) operator.
 By default Method return type is private.
#1. Create a class Box that uses a parameterized method to initialize
the dimensions of a box.(dimensions are width, height, depth of double
type). The class should have a method that can return volume. Obtain
an object and print the corresponding volume in main() function.
>> Run as BoxVol.java
import java.util.Scanner;
class Box{
double width,height,depth; // Instance Variables
Box(double w,double h,double d) { // Constructor
width=w;
height=h;
By- Shalabh Chaudhary [GLAU]
depth=d;
}
double volume() { // Method-Volume
return width*depth*height;
}
}
public class BoxVol { // Main Class
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
double w=scan.nextInt();
double h=scan.nextInt();
double d=scan.nextInt();
Box b= new Box(w,h,d);
System.out.println("Volume is:"+b.volume());
}
}
#2. Create a new class called “Calculator” which contains the
following:
1. A static method called powerInt(int num1,int num2) that accepts two
integers and returns num1 to the power of num2 (num1 power num2).
2. A static method called powerDouble(double num1,int num2) that
accepts one double and one integer and returns num1 to the power of
num2 (num1 power num2).
3. Call your method from another class without instantiating the class
(i.e. call it like Calculator.powerInt(12,10) since your methods are
defined to be static)
Hint: Use Math.pow(double,double) to calculate the power.
>> Run As CalcPower.java
class Calculator{
static double powerInt(int num1,int num2) {
return Math.pow(num1,num2);
By- Shalabh Chaudhary [GLAU]
}
static double powerDouble(double num1,int num2) {
return Math.pow(num1,num2);
}
}
public class CalcPower {
public static void main(String[] args) {
System.out.println(Calculator.powerInt(12,10));
System.out.println(Calculator.powerDouble(12.5,10));
}
}
#3. Design a class that can be used by a health care professional to
keep track of a patient’s vital statistics. Here’s what the class
should do:
1. Construct a class called Patient
2. Store a String name for the patient
3. Store weight and height for patient as doubles
4. Construct a new patient using these values
5. Write a method called BMI which returns the patient’s BMI as a
double. BMI can be calculated as BMI = ( Weight in Pounds / ( Height
in inches x Height in inches ) ) x 703
6. Next, construct a class called “Patients” and create a main method.
Create a Patient object and assign some height and weight to that
object. Display the BMI of that patient.
>> Run as Patients.java
class Patient {
String name;
double weight,height;
Patient(double w,double h){
By- Shalabh Chaudhary [GLAU]
weight=w;
height=h;
}
double BMI() {
return (weight/(height*height))*703;
}
}
public class Patients{
public static void main(String[] args) {
Patient p=new Patient(75,156);
System.out.println("BMI is:"+p.BMI());
}
}
Encapsulation & Abstraction 
 Encapsulation = hiding implementation level details.
 Abstraction = exposing only interface.
Access Specifiers 
 Access specifiers help implement:
 Encapsulation by hiding implementation-level details in a class.
 Abstraction by exposing only the interface of the class to the external world.
 Implementation of Encapsulation & Abstraction -
class Point {
private int x;
private int y;
void setX( int x)
{
x = (x > 79 ? 79 : (x < 0 ? 0 :x)); // this.x=
}
void setY(int y)
{
y = (y > 24 ? 24 : (y < 0 ? 0 : y)); // this.y=
}
int getX()
By- Shalabh Chaudhary [GLAU]
{
return x;
}
int getY()
{
return y;
}
}
class PointDemo {
public static void main(String args[]) {
int a, b;
Point p = new Point();
p.setX(22);
p.setY(44);
System.out.println("The value of a is "+p.getX());
System.out.println("The value of b is "+p.getY());
}
}
>> Output: The value of a is 0
The value of b is 0
Use this.x & this.y in setX and setY mthd to get 22,44 as o/p.
#1. Create a class called Author is designed as follows:
It contains:
• Three private instance variables: name (String), email (String), and
gender (char of either ‘m’ or ‘f’).
• One constructor to initialize the name, email and gender with the
given values.
And, a class called Book is designed as follows:
It contains:
• Four private instance variables: name (String), author (of the class
Author you have just created), price (double), and qtyInStock (int).
Assuming that each book is written by one author.
• One constructor which constructs an instance with the values given.
• Getters and setters: getName(), getAuthor(), getPrice(), setPrice(),
getQtyInStock(), setQtyInStock(). Again there is no setter for name
and author.
Write the class Book (which uses the Author class written earlier).
Try:
By- Shalabh Chaudhary [GLAU]
1. Printing the book name, price and qtyInStock from a Book instance.
(Hint: aBook.getName())
2. After obtaining the “Author” object, print the Author (name, email
& gender) of the book.
>>
class Author {
public static String name,email;
public static char gender;
Author(String n,String e, char g){
name=n;
email=e;
gender=g;
}
}
class Book{
String name1,author;
double price;
int qtyInStock;
Book(String n1){
name1=n1;
}
void setQtyInStock() {
qtyInStock=10;
}
void setPrice() {
price=100.0;
}
double getPrice() {
return price;
}
By- Shalabh Chaudhary [GLAU]
int getQtyInStock() {
return qtyInStock;
}
String getName() {
return name1;
}
void getAuthor() {
System.out.println("Author is:"+Author.name);
System.out.println("Mail id is:"+Author.email);
System.out.println("Gender is:"+Author.gender);
}
}
public class Books{
public static void main(String args[]) {
Book b=new Book("Computer Networks");
Author a=new Author("amy","xxx.cse@rmd.ac.in",'f');
b.setPrice();
b.setQtyInStock();
System.out.println("The name of the book is :"+b.getName());
System.out.println("The price of the book is :"+b.getPrice());
System.out.println("The stock is :"+b.getQtyInStock());
b.getAuthor();
}
}
By- Shalabh Chaudhary [GLAU]
Inheritance 
It allows for the creation of hierarchical classifications.
 Each of these classes will add only those attributes & behaviors that are unique to it.
 Super Class = class that is inherited. [ Base Class / Parent Class ]
 Sub Class = class that does the inheriting. [ Derived Class / Extended Class / child class ]
 Sub class inherits all properties of its superclass.
Basic building blocks of OOPs 
 Association = Relationship between two objects.
 The association could be -
1. one-to-one
2. one-to-many
3. many-to-one
4. many-to-many
 Types of Association –
 Aggregation = A directional association between objects.
Also called a “Has-a” relationship.
Example: College has a Student Object.
 Composition [Restricted Aggregation] = When an object contains other object,
if contained obj. can’t exist without existence of container obj, => compos
Example: A class contains students.
>> Student can’t exist without class.There exists composition b/w class & students.
 Containership = Means using instance variables that refer to other objects.
Inheritance Model 
Java uses Single inheritance model.
Single Inheritance 
In single inheritance, a subclass can inherit from one(and only one) super class.
Syntax:
class derived-class-name extends base-class-name {
//code goes here
}
Eg.:
 class A {
int m, n;
void display1( ) { System.out.println("m and n are:"+m+" "+n); }
}
class B extends A {
int c;
void display2() { System.out.println("c :"+ c); }
void sum() { System.out.println("m+n+c= "+ (m+n+c)); }
}
class Main {
By- Shalabh Chaudhary [GLAU]
public static void main(String args[ ]) {
A s1= new A(); // creating objects
B s2= new B();
s1.m= 10; s1.n= 20;
System.out.println("State of object A:");
s1.display1();
s2.m= 7;
s2.n= 8;
s2.c= 9;
System.out.println("State of object B:");
s2.display1();
s2.display2();
System.out.println("sum of m, n and c in object B is:");
s2.sum();
}
}
 Accessing Superclass Members from a Subclass Object 
 A sub class includes all of the members of its super class.
But, it cannot directly access those members of the super class that
have been declared as private.
Eg.:
class A {
int money;
private int pocketMoney;
void fill(int money,int pocketMoney) {
this.money=money;
this.pocketMoney= pocketMoney;
}
}
class B extends A {
int total;
void sum( ) {
total = money + pocketMoney;
}
}
class AccessDemo { public static void main(String args[ ]) {
B subob= new B();
subob.fill(10,12);
subob.sum();
System.out.println("Total: " + subob.total);
}
}
By- Shalabh Chaudhary [GLAU]
Using super 
 When a subclass object is created, It creates the super class object.
 The constructors of the super class are never inherited by the subclass.
 super keyword is used ->
1. To differentiate the members of superclass from the members of subclass, if
they have same names.
2. To invoke the superclass constructor from subclass.
 Eg.:
package mypack;
class Employee{
int Employeeno;
String Empname;
Employee() {
System.out.println(" Employee No-argConstructor Begins");
Employeeno=0;
Empname= null;
System.out.println(" Employee No-argConstructor Ends");
}
Employee(int Employeeno) {
System.out.println(" Employee 1-arg Constructor Begins");
this.Employeeno=Employeeno;
this.Empname= "UNKNOWN";
System.out.println(" Employee 1-arg Constructor Ends");
}
Employee(int Employeeno, String s) {
System.out.println(" Employee 2-arg Constr Begins");
this.Employeeno= Employeeno;
this.Empname= s;System.out.println("Emp 2-arg Constr Ends");
}
void display(){
System.out.println(" Employee Number = "+Employeeno);
System.out.println(" Employee Name = "+Empname);
}
}
class Manager extends Employee {
String deptname;
Manager(int Employeeno, String name, String deptname){
super(Employeeno, name);
System.out.println(" Manager 3-arg Constr Begins");
this.deptname= deptname;
System.out.println(" Manager 3-arg Construct Ends");
}
void display(){
super.display();
System.out.println(" Deptname= "+deptname);
}
By- Shalabh Chaudhary [GLAU]
public static void main( String a[]) {
System.out.println(" [Main function Begins---] ");
System.out.println("Creating object for manager class");
Manager mm = new Manager(10,"Gandhi","Banking");
System.out.println(" Printintthe manager details: ");
mm.display();
System.out.println(" [Main function Ends----]");
}
}
Using super to Call Superclass Constructors 
super() - Always be the first statement executed inside a subclass constructor.
- Tells order of invocation of constructors in a class hierarchy.
 Constructors in a class hierarchy are invoked in the order of their derivation.
Using this() in a constructor 
 this(arg_ list) stmt invokes the constructor of the same class.
 First line of a constructor must EITHER be a super(call on the super class
constructor) OR a this(call on the constructor of same class).
 If the first statement within a constructor is NEITHER super() NOR this(), then
compiler will automatically insert a super(). [ i.e., invocation to the super class no
argument constructor].
OUTPUT BASED 
 class A1 {
A1() {
System.out.println("A1's no arg constructor");
}
A1(int a) {
System.out.println("A1's constructor "+ a);
}
}
class B1 extends A1 {
B1(){
System.out.println("B1's no arg constructor");
}
B1(int b){
super(1000);
System.out.println("B1's constructor "+ b);
}
}
class C1 extends B1{
C1() {
By- Shalabh Chaudhary [GLAU]
System.out.println("C1's no arg constructor");
}
C1(int c){
super(100);
System.out.println("C1's constructor "+ c);
}
}
class TestingInheritance{
public static void main(String args[]){
C1 ca = new C1();
}
}
>> Output:
A1's no arg constructor
B1's no arg constructor
C1's no arg constructor
 class A1 {
A1(){
System.out.println("A1's no arg constructor");
}
A1(int a) {
System.out.println("A1's constructor "+ a);
}
}
class B1 extends A1{
B1(){
System.out.println("B1's no arg constructor");
}
B1(int b){
super(1000);
System.out.println("B1's constructor "+ b);
}
}
class C1 extends B1{
C1() {
System.out.println("C1's no arg constructor");
}
C1(int c){
super(100);
System.out.println("C1's constructor "+ c);
}
}
class TestingInheritance {
public static void main(String args[]){
C1 ca = new C1(10);
By- Shalabh Chaudhary [GLAU]
}
}
>> Output:
A1's constructor 1000
B1's constructor 100
C1's constructor 10
 class A1 {
A1(){
System.out.println("A1's no arg constructor");
}
A1(int a){
System.out.println("A1's constructor "+ a);
}
}
class B1 extends A1{
B1(){
System.out.println("B1's no arg constructor");
}
B1(int b){
super(1000);
System.out.println("B1‘s constructor "+ b);
}
}
class C1 extends B1{
C1() {
System.out.println("C1's no arg constructor");
}
C1(int c){
System.out.println("C1's constructor "+ c);
}
}
class TestingInheritance{
public static void main(String args[]){
C1 ca = new C1(10);
}
}
>> Output- A1's no arg constructor
B1's no arg constructor
C1's constructor 10
 class A1 {
A1(){
System.out.println("A1's no arg constructor");
}
A1(int a){
By- Shalabh Chaudhary [GLAU]
System.out.println("A1's constructor "+ a);
}
}
class B1 extends A1{
B1(){
System.out.println("B1's no arg constructor");
}
B1(int b){
System.out.println("B1‘s constructor "+ b);
}
}
class C1 extends B1{
C1() {
super(100);System.out.println("C1's no arg constructor");
}
C1(int c){
System.out.println("C1's constructor "+ c);
}
}
class TestingInheritance{
public static void main(String args[]){
C1 ca = new C1(10);
}
}
>> Output: A1's no arg constructor
B1's no arg constructor
C1's constructor 10
 class A1 {
A1(){
System.out.println("A1's no arg constructor");
}
A1(int a){
System.out.println("A1's constructor "+ a);
}
}
class B1 extends A1{
B1(){
super(50);
System.out.println("B1's no arg constructor");
}
B1(int b){
super(1000);
System.out.println("B1‘s constructor "+ b);
}
By- Shalabh Chaudhary [GLAU]
}
class C1 extends B1{
C1() {
System.out.println("C1's no arg constructor");
}
C1(int c){
System.out.println("C1's constructor "+ c);
}
}
class TestingInheritance{
public static void main(String args[]){
C1 ca = new C1(10);
}
}
>> Output- A1's constructor 50
B1's no arg constructor
C1's constructor 10
 class A1 {
A1(){
System.out.println("A1's no arg constructor");
}
A1(int a){
System.out.println("A1's constructor "+ a);
}
}
class B1 extends A1{
B1(){
System.out.println("B1's no arg constructor");
}
B1(int b){
this("x");
System.out.println("B1's constructor "+ b);
}
B1(String b){
super(1000);
System.out.println("B1's constructor "+ b);
}
}
class C1 extends B1{
C1() {
System.out.println("C1's no arg constructor");
}
C1(int c){
super(100);
System.out.println("C1's constructor "+ c);
By- Shalabh Chaudhary [GLAU]
}
}
class TestingInheritance {
public static void main(String args[]){
C1 ca = new C1(10);
}
}
>> Output: A1's constructor 1000
B1's constructor x
B1's constructor 100
C1's constructor 10
Multilevel Hierarchy 
A derived class will be inheriting a base class and as well as the derived class also
act as the base class to other class.
 class student
{
int rollno;
String name;
student(int r, String n)
{
rollno = r;
name = n;
}
void dispdatas()
{
System.out.println("Rollno = " + rollno);
System.out.println("Name = " + name);
}
}
class marks extends student
{
int total;
marks(int r, String n, int t)
{
super(r,n); //call super class (student) constructor
total = t;
}
By- Shalabh Chaudhary [GLAU]
void dispdatam()
{
dispdatas(); // call dispdatap of student class
System.out.println("Total = " + total);
}
}
class percentage extends marks
{
int per;
percentage(int r, String n, int t, int p)
{
super(r,n,t); //call super class(marks) constructor
per = p;
}
void dispdatap()
{
dispdatam(); // call dispdatap of marks class
System.out.println("Percentage = " + per);
}
}
class Multi_Inhe
{
public static void main(String args[])
{
percentage stu = new percentage(102689, "VINEETH", 350, 70); //call
constructor percentage
stu.dispdatap(); // call dispdatap of percentage class
}
}
By- Shalabh Chaudhary [GLAU]
Hierarchical Inheritance 
one class serves as a superclass (base class) for more than one sub class.In below
image, the class A serves as a base class for the derived class B,C and D.
 class A {
public void methodA() {
System.out.println("Class A Mthd");
}
}
class B extends A {
public void methodB(){
System.out.println("Class B Mthd");
} }
class C extends A {
public void methodC() {
System.out.println("method of Class C");
}
}
class D extends A {
public void methodD() {
System.out.println("method of Class D");
}
}
class HierarchInheritance {
public static void main(String args[]) {
B obj1 = new B();
C obj2 = new C();
D obj3 = new D();
//All classes can access the method of class A
obj1.methodA();
obj2.methodA();
obj3.methodA();
}
}
Java does NOT Support Multiple Inheritance with classes.
By- Shalabh Chaudhary [GLAU]
Multiple Inheritance [Through Interfaces] 
One class can have more than one superclass and inherit features from all parent
classes.
 interface PI1 {
// default method
default void show() {
System.out.println("Default PI1");
}
}
interface PI2 {
// Default method
default void show() {
System.out.println("Default PI2");
}
}
// Implementation class code
class TestClass implements PI1, PI2 {
// Overriding default show method
public void show() {
// use super keyword to call the show
// method of PI1 interface
PI1.super.show();
// use super keyword to call the show
// method of PI2 interface
PI2.super.show();
}
public static void main(String args[]) {
TestClass d = new TestClass();
d.show();
}
}
Hybrid Inheritance [Through Interfaces] 
It is a mix of two or more of the above types of inheritance.
 public class ClassA {
public void dispA(){
System.out.println("Class A Mthd");
}
}
public interface InterfaceB {
public void show();
}
By- Shalabh Chaudhary [GLAU]
public interface InterfaceC {
public void show();
}
public class ClassD implements InterfaceB,InterfaceC {
public void show() {
System.out.println("show() method implementation");
}
public void dispD() {
System.out.println("disp() method of ClassD");
}
public static void main(String args[]) {
ClassD d = new ClassD();
d.dispD();
d.show();
}
}
#1. Create a class named ‘Animal’ which includes methods like eat()
and sleep().
Create a child class of Animal named ‘Bird’ and override the parent
class methods. Add a new method named fly().
Create an instance of Animal class and invoke the eat and sleep
methods using this object. Create an instance of Bird class and invoke
the eat, sleep and fly methods using this object.
>>
class Animal {
void eat() {
System.out.println("eat Mthd");
}
void sleep() {
System.out.println("sleep Mthd");
}
}
class Bird extends Animal{
@Override
void eat() {
System.out.println("Override eat Mthd");
By- Shalabh Chaudhary [GLAU]
}
void sleep() {
System.out.println("Override sleep Mthd");
}
void fly() {
System.out.println("fly method");
}
}
class AnimalsDemo{
public static void main(String args[]) {
Animal a = new Animal();
Bird b= new Bird();
a.eat();
a.sleep();
b.eat();
b.sleep();
b.fly();
}
}
#2. Create class called Person with a member variable name. Save it in
file called Person.java
Create a class called Employee who will inherit the Person class.The
other data members of the employee class are annual salary (double),
the year the employee started to work, and the national insurance
number which is a String. Save this in a file called Employee.java
Your class should have a reasonable number of constructors and
accessor methods.
Write another class called TestEmployee, containing a main method to
fully test your class definition.
>> Person.java
public class Person {
private String name;
By- Shalabh Chaudhary [GLAU]
public Person(String n){
name=n;
}
public void setName(String n) {
name=n;
}
public String getName() {
return name;
}
public String toString(){
return name;
}
}
----x----x----x----
Employee.java
public class Employee extends Person {
private double annual_salary;
private int emp_yr;
private String insurance_no;
public Employee(String n,double a, int y, String i){
super(n);
annual_salary=a;
emp_yr=y;
insurance_no=i;
}
public void setSalary(double a) {
annual_salary=a;
}
public void setYear(int y) {
By- Shalabh Chaudhary [GLAU]
emp_yr=y;
}
public void setInsurance_no(String i) {
insurance_no=i;
}
public double getSalary() {
return annual_salary;
}
public int getYear() {
return emp_yr;
}
public String getInsurance_no() {
return insurance_no;
}
public String toString() {
return super.toString()+" "+annual_salary+" "+emp_yr+"
"+insurance_no;
}
}
----x----x----x----
TestEmployee.java
public class TestEmployee {
public static void main(String[] args) {
Person p= new Person("Anil");
Employee e=new Employee("Jim",10000, 2015, "abcd");
System.out.println(p);
System.out.println(e);
}
}
By- Shalabh Chaudhary [GLAU]
Method Overriding [ Polymorphism ] 
When a method in a subclass has the same prototype as a method in the
superclass, then the method in the subclass is said to override the method in the
super class.
 Same prototype - Means has the same name, type signature (the same type,
sequence and number of parameters), and the same return type as the method
in its super class.
 class A {
int a,b;
A(int m, int n) {
a = m;
b = n;
}
void display() {
System.out.println("a and b are: "+a+" "+b);
}
}
class B extends A {
int c;
B(int m, int n, int o) {
super(m,n);
c = o;
}
void display() {
System.out.println("c :" + c);
}
}
class OverrideDemo {
public static void main(String args[]) {
B subOb= new B(4,5,6);
subOb.display();
}
}
>> Output- c:6
// display() inside B overrides display declared in its superclass, i.e., class A.
By- Shalabh Chaudhary [GLAU]
Using super to Call an Overridden Method 
 class A {
int a,b;
A(int m, int n) {
a = m;
b = n;
}
void display() {
System.out.println("a and b are :"+a+" "+b);
}
}
class B extends A {
int c;
B(int m, int n, int o) {
super(m,n);
c = o;
}
void display() {
super.display();
System.out.println("c :" + c);
}
}
class OverridewithSuper {
public static void main(String args[]) {
B subOb= new B(4,5,6);
subOb.display();
}
}
>> Output- a and b are: 4 5
c: 6
// Method overriding occurs only when the names and the type signatures of two
methods across atleast two classes (i.e., a superclass and a subclass) in a class
hierarchy are identical.
If they are not, then the two methods are simply overloaded.
By- Shalabh Chaudhary [GLAU]
Superclass Reference Variable 
A reference variable of type superclass can be assigned a reference to any subclass
object derived from that super class.
 class A1{ }
class A2 extends A1{ }
class A3 {
public static void main(String[]args) {
A1 x;
A2 z=newA2();
x=new A2(); //valid
z=new A1(); //invalid
}
}
Superclass Reference Variable Can Reference a Subclass Object 
 Method calls in java are resolved dynamically at runtime.
Rules for Method Overriding 
 Must have the same argument list.
 Must have the same return type.
 Must not have a more restrictive access modifier
 May have a less restrictive access modifier
 Must not throw new or broader checked exceptions
 May throw fewer or narrower checked exceptions or any unchecked exceptions.
 Final methods cannot be overridden.
 Constructors cannot be overridden.
OUTPUT BASED 
 class A1 {
void m1() {
System.out.println("In method m1 of A1");
}
}
class A2 extends A1 {
int m1() {
return 100;
}
public static void main(String[] args) {
A2 x = new A2();
x.m1();
}
}
// Error: m1() in A2 cannot override m1() in A1.
By- Shalabh Chaudhary [GLAU]
QQ. Why Overridden Methods ?
Ans: So, that subclass will override the method in superclass.
Dynamic Method Dispatch [ Runtime Polymorphism ] 
 Occurs when the Java language resolves a call to an overridden method at
runtime, and, in turn, implements runtime polymorphism.
 Mechanism by which a call to an overridden method is resolved at run time,
rather than compile time.
 Run time polymorphism possible in class hierarchy with the help of its features:
1. Overridden Methods.
2. Super class Reference variables. - Can hold reference to subclass object.
 When an overridden method is called through a super class reference, Java
determines which method to call based upon the type of the object being referred
to at the time the call occurs.
 class Figure{
double dimension1; double dimension2;
Figure(double x,double y){
dimension1=x; dimension2=y;
}
double area(){
System.out.println("Area of Figure is undefined");
return 0;
}
}
class Rectangle extends Figure{
Rectangle(double x,double y){
super(x,y);
}
double area() { //method overriding
System.out.print("Area of rectangle is :");
return dimension1 * dimension2;
}
}
class Triangle extends Figure {
Triangle(double x, double y) {
super(x,y);
}
double area() { //method overriding
System.out.print("Area for triangle is :");
return dimension1 * dimension2 / 2;
}
}
class FindArea {
public static void main(String args[]) {
By- Shalabh Chaudhary [GLAU]
Figure f=new Figure(10,10);
Rectangle r= new Rectangle(9,5);
Triangle t= new Triangle(10,8);
Figure fig; //reference variable
fig=r;
System.out.println("Area of rect is:"+fig.area());
fig=t;
System.out.println("Area of triangle is:"+fig.area());
fig=f;
System.out.println(fig.area());
}
}
instanceof Operator 
 Use of instance of operator :
 Allows to determine the type of an object.
 Compares an object with a specified type.
 Takes an object and a type and returns true if object belongs to that type &
returns false otherwise.
 Used to test if an object is an instanceof a class, an instanceof a subclass, or an
instanceof a class that implements an interface.
 class A { int i, j;
}
class B extends A {
int a, b;
}
class C extends A {
int m, n;
}
class instanceOf{
public static void main(String args[]) {
A a= new A( );
B b= new B( );
C c= new C( );
A ob=b;
if (ob instanceof B)
System.out.println("ob now refers to B");
else
System.out.println("Ob is not instance of B");
if (ob instanceof A)
System.out.println("ob is also instance of A");
else
System.out.println("Ob is not instance of A");
if (ob instanceof C)
By- Shalabh Chaudhary [GLAU]
System.out.println("ob now refers to C");
else
System.out.println("Ob is not instance of C");
}
}
The Cosmic Class – The Object Class 
 Available in java.lang package
 Object is superclass of all other classes; i.e., Java’s own classes, as well as
user-defined classes.
 This means that a reference variable of type Object can refer to an object of any
other class.
#1. Create a base class Fruit which has name ,taste and size as its
attributes. A method called eat() is created which describes the name
of the fruit and its taste. Inherit the same in 2 other class Apple
and Orange and override the eat() method to represent each fruit
taste.
>>
class Fruit {
String name,taste,size;
Fruit(String n,String t,String s) {
name=n;
taste=t;
size=s;
}
void eat() {
System.out.println(name+" "+taste);
}
}
class Apple extends Fruit{
Apple(String n, String t, String s) {
super(n, t, s);
}
@Override
By- Shalabh Chaudhary [GLAU]
void eat() {
System.out.println(name+" "+taste);
}
}
class Orange extends Fruit{
Orange(String n, String t, String s) {
super(n, t, s);
}
@Override
void eat() {
System.out.println(name+" "+taste);
}
}
public class FruitCheck{
public static void main(String args[]) {
Apple a= new Apple("Apple","Sweet","Heart");
Orange o=new Orange("Orange","Sour","Round");
a.eat();
o.eat();
}
}
#2. Write a program to create a class named shape. It should contain 2
methods- draw() and erase() which should print “Drawing Shape” and
“Erasing Shape” respectively.
For this class we have three sub classes- Circle, Triangle and Square
and each class override the parent class functions- draw() & erase().
The draw() method should print “Drawing Circle”, “Drawing Triangle”,
“Drawing Square” respectively.
The erase() method should print “Erasing Circle”, “Erasing Triangle”,
“Erasing Square” respectively.
By- Shalabh Chaudhary [GLAU]
Create objects of Circle, Triangle and Square in the following way and
observe the polymorphic nature of the class by calling draw() and
erase() method using each object.
Shape c=new Circle();
Shape t=new Triangle();
Shape s=new Square();
>>
class Shape {
void draw() {
System.out.println("Drawing Shape");
}
void erase() {
System.out.println("Erasing Shape");
}
}
class Circle extends Shape{
@Override
void draw() {
System.out.println("Drawing Circle");
}
void erase() {
System.out.println("Erasing Circle");
}
}
class Triangle extends Shape{
@Override
void draw() {
System.out.println("Drawing Triangle");
}
void erase() {
System.out.println("Erasing Triangle");
By- Shalabh Chaudhary [GLAU]
}
}
class Square extends Shape{
@Override
void draw() {
System.out.println("Drawing Square");
}
void erase() {
System.out.println("Erasing Square");
}
}
public class Polymorphism{
public static void main(String args[]) {
Shape c=new Circle();
Shape t=new Triangle();
Shape s=new Square();
c.draw();
c.erase();
t.draw();
t.erase();
s.draw();
s.erase();
} }
By- Shalabh Chaudhary [GLAU]
Garbage Collection 
 Once the program completes, These objects become garbage...
 Java’s Cleanup Mechanism – The Garbage Collector :
 Java has its own Garbage Collector
 Test test=new Test(); // Obj. test created & memory allocated for this obj.
 test=null;  When you execute this, the reference is deleted but the memory
occupied by the object is not released.
 To release the memory occupied by the ‘test ’object -
 Objects on the heap must be deallocated or destroyed, and their memory
released for later reallocation.
 Java handles object deallocation automatically through garbage collection.
 The Garbage Collection is done automatically by JVM.
 To manually do the garbage collection, Use method:
Runtime rs= Runtime.getRuntime();
rs.gc();
>> gc() method is used to manually run the garbage collection.
 The rs.freeMemory() method - Give free memory available in the system.
The finalize() Method 
Using finalization, can define specific actions that will occur when an object is just
about to be reclaimed by the garbage collector.
 Inside finalize() method, specify actions that must be performed before object is
destroyed.
 Java runtime calls this method whenever it’s about to recycle an object of class.
Eg.:
 public class CounterTest{
public static int count;
public CounterTest( ) {
count++;
}
public static void main(String args[ ]) {
CounterTest ob1 = new CounterTest( ) ;
System.out.println("Number of objects :" + CounterTest.count) ;
CounterTest ob2 = new CounterTest( );
Runtime r = Runtime.getRuntime( );
ob1 = null;
ob2 = null;
r.gc( );
By- Shalabh Chaudhary [GLAU]
}
protected void finalize( ) {
System.out.println("Program about to terminate");
CounterTest.count--;
System.out.println("Number of objects :" + CounterTest.count) ;
}
}
>> Output: Number of objects: 1
Number of objects: 2
Program about to terminate
Number of objects: 1
Program about to terminate
Number of objects: 0
 The class A3 cannot be subclass of the final class A2.
 Cannot override the final method from parent class A1.
String and StringBuffer 
 String is a group of characters.They are objects of type String
 Strings are Immutable – Once obj. created CAN’T be changed.
 To get changeable strings use the class called StringBuffer.
 String and StringBuffer classes are declared as final,
So, there CAN NOT be sub classes of these classes.
 The default constructor creates an empty string.
String s=new String();
 Handling Strings:
String str = "abc"; // Empty String  String str = "";
Is equivalent to:
char data[] = {'a', 'b', 'c'};
>> If data array in the above is modified after the string object str is created, then str
remains unchanged.
 String Creation using new Keyword:
String str1 = new String("abc");
String str2 = new String("abc");
If(str1==str2) // true same  String objects reference are not same.
 String class Methods:
 str.length() – System.out.println("shalabh".length() ) // Prints 7
or int len = str.length();
 str1+str2 operator – Concatenate 2 or more Strings.
By- Shalabh Chaudhary [GLAU]
System.ot.println(str1+str2); // str1 and str2 are 2 strings.
 str.charAt(i) - Retrieve Character in a String.
char c = str.charAt(1); // Prints b if str = "abc";
 str1.equals(str2) – Returns true if 2 strings are same.
or
>> str1==str2 – Returns true if both string matched.  str obj. reference is same
 str1.equalsIgnoreCase(str2) – Returns true if 2 string are same even case not
matched in both strings.
 str1.startsWith(str2) – Tests if string start with specified prefix.
"January".startsWith("Jan"); // true
 str1.endsWith(str2) – Tests if string ends with specified suffix.
"December".endsWith("ber"); // true
 str1.compaerTo(str2) – Checks string is bigger or smaller.
returns -ve integer if str1 < str2
returns +ve integer if str1 > str2
returns 0 if str1 = str2
Eg.: "Hel".compareToIgnoreCase("hello") // Prints -2 (differ by strings)
"Hel".compare("hello") // Prints -32 (H to h differ by -32)
 str1.indexOf(str2) – Searches for first Occurrence of character or substring.
"Hello".indexOf("l") // Prints 2 i.e., 2nd
index.
returns -1 if character or string not occurs.
 str1.indexOf(str2, fromIndex) – Search character ch within string & return
index of first occurrence of this character start from pos fromIndex.
Eg.: String str="How was your day today?";
str.indexOf('a',6); // Prints 14 (at 14th
index a prsnt)
str.indexOf("was", 2); // Prints 4 (from 4th
index “was” starts)
 str1.lastIndexOf(str2) - Searches last occurrence of particular string or character
 str1.substring(beginIndex, endIndex) – Returns new string which is substring
of string str1
Eg.: "Unhappy".substring(2) // Prints happy.
"Smiles".substring(1,5) // Prints mile [ endIndex=5 i.e.,5-1= till 4th
]
 str1.concat(str2) – Concatenate specified string(str2) to end of string.
"to".concat("get").concat("her") // Prints “together”
By- Shalabh Chaudhary [GLAU]
 str1.replace(oldChar, newChar) – Return new string - replace oldChar with new
"Wipra Technalagies".replace('a', 'o')
>> Prints Wipro Technologies.
 valueOf(ar) – Convert character array into string.
Result is string representation of argument passed as char array.
 str1.toLoweCase() - "HELLO WORLD".toLowerCase();
 str1.toUpperCase() - "hello world".toUpperCase();
 StringBuffer 
 String Buffer class objects are mutable, so they can be modified.
StringBuffer sb = new StringBufer();
 String Buffer class defines three constructors:
1. StringBuffer() //empty object
2. StringBuffer(int capacity) //creates empty obj with capacity for storing string
3. StringBuffer(String str) //createStringBufferobjectbyusingastring
 StringBuffer Operations:
1. sb.append(str) - adds specified characters at end of StringBuffer object.
StringBuffer append(int index, char ch) // indx- pt. where str insrt.
2. sb.insert(indx, str) - To insert characters at specified index location.
StringBuffer insert(int index, String str)
>> Both methods are overloaded so they can accept any type of data.
3. sb.delete(startIndex, endIndex) - Delete specified substring in StringBuffer.
StringBuffer delete(int start, int end)
4. sb.replace() - Replace part of StringBuffer(substring) with another substring.
StringBuffer replace(int start, int end, String str)
5. sb.substring(startIndx, endIndx) - Return new string i.e., StringBuffer’s substr
String substring(int start) // prints endIndx-1
>> It extracts characters starting from the specified index till the end of the StringBuffer.
6. sb.reverse() - Character sequence is reversed.
7. sb.length() – To find length of StringBuffer.
8. sb.capacity() – To find capacity of StringBuffer.
>> Capacity - Amount of storage available for characters that have just been inserted.
By- Shalabh Chaudhary [GLAU]
9. sb.charAt(indx) – Find character at particular index position.
10. sb.deletecharAt(indx) – delete character at particular index.
Eg.: StringBuffer sb= new StringBuffer("Wipro Technologies");
String result = sb.substring(6); // only startIndex prst
System.out.println(result); // Prints Technologies
#1. Write a Program that will check whether a given String is
Palindrome or not
>>
import java.util.Scanner;
public class PalindromeString {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
String s=scan.nextLine();
StringBuffer sb=new StringBuffer(s);
sb.reverse();
if(s.equalsIgnoreCase(sb.toString()))
System.out.println("Palindrome");
else
System.out.println("Not Palindrome");
}
}
#2. Given two strings, append them together (known as "concatenation")
and return the result. However, if the concatenation creates a double-
char, then omit one of the chars. If the inputs are “Mark” and “Kate”
then the ouput should be “markate”. (The output should be in
lowercase)
>>
import java.util.Scanner;
public class AppendString {
By- Shalabh Chaudhary [GLAU]
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
String s1=scan.nextLine();
String s2=scan.nextLine();
if(s1.substring(s1.length()-1).equalsIgnoreCase( s2.substring(0,1)))
System.out.println(s1.concat(s2.substring(1,s2.length())));
else
System.out.println(s1.concat(s2).toLowerCase()); } }
#3. Given string, return new string made of n copies of first 2 chars
of the original string where n is the length of the string. The string
may be any length. If there are fewer than 2 chars, use whatever is
there.
If input is "Wipro" then output should be "WiWiWiWiWi".
>>
public class Copy2Chars{
static String charCopy(String s,int n) {
String res="";
if(n<2)
return s;
else {
s=s.substring(0,2);
while(n!=0) {
res=res.concat(s);
n--;
}
return res;
}
}
public static void main(String args[]) {
String s="Wipro";
int n=s.length();
By- Shalabh Chaudhary [GLAU]
System.out.print(charCopy(s,n));
}
}
#4. Given a string, if the first or last chars are 'x', return the
string without those 'x' chars, and otherwise return the string
unchanged. If the input is "xHix", then output is "Hi".
>>
public class Trimxx{
static String trim(String s,int n) {
if (n==1){
if (s.charAt(0) == 'x')
return "";
else
return s;
}
if(s.charAt(0)=='x' && s.charAt(n-1)=='x')
s=s.substring(1,n-1);
return s;
}
public static void main(String args[]) {
String s="xHix";
int n=s.length();
System.out.print(trim(s,n));
}
}
By- Shalabh Chaudhary [GLAU]
#5. Given two strings, word and a separator, return a big string made
of count occurrences of the word, separated by the separator string.
if the inputs are "Wipro","X" and 3 then the output is
"WiproXWiproXWipro".
>>
public class StringtillCount{
static String strCount(String s,int sep) {
String res="";
while(sep>0) {
res+=s.concat("X");
sep--;
}
res=res.substring(0,res.length()-1);
return res;
}
public static void main(String args[]) {
String s="Wipro";
int sep=3;
System.out.print(strCount(s,sep));
}
}
#6. Return a version of the given string, where for every star (*) in
the string the star and the chars immediately to its left and right
are gone. So "ab*cd" yields "ad" and "ab**cd" also yields "ad".
>>
public class RemoveStar{
static String rmvStr(String s) {
StringBuffer sb=new StringBuffer(s);
int i=s.indexOf('*');
int l=s.lastIndexOf('*');
return new String(sb.delete(i-1,l+2));
}
By- Shalabh Chaudhary [GLAU]
public static void main(String args[]) {
String s="ab**cd";
System.out.print(rmvStr(s));
}
}
#7. Given two strings, a and b, create a bigger string made of the
first char of a, the first char of b, the second char of a, the second
char of b, and so on. Any leftover chars go at the end of the result.
If the inputs are "Hello" and "World", then the output is
"HWeolrllod".
>>
public class AlternatePrint{
static String alter(String a,String b) {
String res="";
int alen=a.length();
int blen=b.length();
int len=Math.min(alen,blen);
int i=0;
while(i<len) {
res+=a.substring(i,i+1)+b.substring(i,i+1);
i++;
}
if(alen!=blen)
res+=b.substring(len);
if(blen!=alen)
res+=a.substring(len);
return res;
}
public static void main(String args[]) {
String a="Hello";
String b="World";
By- Shalabh Chaudhary [GLAU]
System.out.print(alter(a,b));
}
}
#8. Given a string and a non-empty word string, return a string made
of each char just before and just after every appearance of the word
in the string. Ignore cases where there is no char before or after the
word, and a char may be included twice if it is between two words.
If inputs are "abcXY123XYijk" and "XY", output should be "c13i".
If inputs are "XY123XY" and "XY", output should be "13".
If inputs are "XY1XY" and "XY", output should be "11".
>>
public class WordEnds {
static String wordAppear(String s, String w) {
int slen=s.length();
int wlen=w.length();
String res="";
for (int i=0;i<slen-wlen+1;i++) {
String tmp=s.substring(i,i+wlen);
if (i>0 && tmp.equals(w))
res+=s.substring(i-1,i);
if (i<slen-wlen && tmp.equals(w))
res+=s.substring(i+wlen,i+wlen+1);
}
return res;
}
public static void main(String args[]) {
String s="abcXY123XYijk";
String w="XY";
System.out.print(wordAppear(s,w));
}
}
By- Shalabh Chaudhary [GLAU]
INTERVIEW QUESTIONS 
Q: Explain carefully what null means in Java, and why this special value is necessary.
Q: When do we declare a method or class as final explain with example?
Q: When do we declare the members of the class as static explain with example?
Q: Explain about inner classes with an example?
Q: Explain how super keyword is used in overriding the methods?
Q: Explain the use of super() method in invoking a constructor?
Q: When does a base class variable get hidden, Give reasons?
Q: Explain with an example how we can access a hidden base class variable?

More Related Content

What's hot (20)

Javapolymorphism
JavapolymorphismJavapolymorphism
Javapolymorphism
karthikenlume
 
Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statements
Kuppusamy P
 
Operator overloading and type conversion in cpp
Operator overloading and type conversion in cppOperator overloading and type conversion in cpp
Operator overloading and type conversion in cpp
rajshreemuthiah
 
Inheritance
InheritanceInheritance
Inheritance
Sapna Sharma
 
Java Arrays
Java ArraysJava Arrays
Java Arrays
Jussi Pohjolainen
 
Dynamic method dispatch
Dynamic method dispatchDynamic method dispatch
Dynamic method dispatch
yugandhar vadlamudi
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
Pavith Gunasekara
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
Jussi Pohjolainen
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
Kumar Gaurav
 
Packages in java
Packages in javaPackages in java
Packages in java
Elizabeth alexander
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Tech_MX
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Raghu nath
 
Methods in java
Methods in javaMethods in java
Methods in java
chauhankapil
 
Java Programming
Java ProgrammingJava Programming
Java Programming
Anjan Mahanta
 
Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets
Hitesh-Java
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
moazamali28
 
Abstract class and Interface
Abstract class and InterfaceAbstract class and Interface
Abstract class and Interface
Haris Bin Zahid
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
Raja Sekhar
 
SQLITE Android
SQLITE AndroidSQLITE Android
SQLITE Android
Sourabh Sahu
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
thinkphp
 
Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statements
Kuppusamy P
 
Operator overloading and type conversion in cpp
Operator overloading and type conversion in cppOperator overloading and type conversion in cpp
Operator overloading and type conversion in cpp
rajshreemuthiah
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Tech_MX
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Raghu nath
 
Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets
Hitesh-Java
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
moazamali28
 
Abstract class and Interface
Abstract class and InterfaceAbstract class and Interface
Abstract class and Interface
Haris Bin Zahid
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
thinkphp
 

Similar to OOPs & Inheritance Notes (20)

Lecture_4_Static_variables_and_Methods.pptx
Lecture_4_Static_variables_and_Methods.pptxLecture_4_Static_variables_and_Methods.pptx
Lecture_4_Static_variables_and_Methods.pptx
IkaDeviPerwitasari1
 
Lecture 6.pptx
Lecture 6.pptxLecture 6.pptx
Lecture 6.pptx
AshutoshTrivedi30
 
6. static keyword
6. static keyword6. static keyword
6. static keyword
Indu Sharma Bhardwaj
 
Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry Level
Ramrao Desai
 
Pi j2.3 objects
Pi j2.3 objectsPi j2.3 objects
Pi j2.3 objects
mcollison
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
BG Java EE Course
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptx
chetanpatilcp783
 
Ch. 6 -Static Class Members.ppt programming
Ch. 6 -Static Class Members.ppt programmingCh. 6 -Static Class Members.ppt programming
Ch. 6 -Static Class Members.ppt programming
adamjarrah2006
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword ppt
Vinod Kumar
 
Class and Object.pptx from nit patna ece department
Class and Object.pptx from nit patna ece departmentClass and Object.pptx from nit patna ece department
Class and Object.pptx from nit patna ece department
om2348023vats
 
Java basics
Java basicsJava basics
Java basics
Shivanshu Purwar
 
Object and class
Object and classObject and class
Object and class
mohit tripathi
 
PPT Lecture-1.4.pptx
PPT Lecture-1.4.pptxPPT Lecture-1.4.pptx
PPT Lecture-1.4.pptx
HimanshuPandey957216
 
Java Basics - Part2
Java Basics - Part2Java Basics - Part2
Java Basics - Part2
Vani Kandhasamy
 
Java Basic day-2
Java Basic day-2Java Basic day-2
Java Basic day-2
Kamlesh Singh
 
Session 3 Constructors, Types, Overloading, Static MethodsNotes.pdf
Session 3 Constructors, Types, Overloading, Static MethodsNotes.pdfSession 3 Constructors, Types, Overloading, Static MethodsNotes.pdf
Session 3 Constructors, Types, Overloading, Static MethodsNotes.pdf
tabbu23
 
Class and Object JAVA PROGRAMMING LANG .pdf
Class and Object JAVA PROGRAMMING LANG .pdfClass and Object JAVA PROGRAMMING LANG .pdf
Class and Object JAVA PROGRAMMING LANG .pdf
sameer2543ynr
 
03_Objects and Classes in java.pdf
03_Objects and Classes in java.pdf03_Objects and Classes in java.pdf
03_Objects and Classes in java.pdf
Parameshwar Maddela
 
Lab 4
Lab 4Lab 4
Lab 4
vaminorc
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Tushar B Kute
 
Lecture_4_Static_variables_and_Methods.pptx
Lecture_4_Static_variables_and_Methods.pptxLecture_4_Static_variables_and_Methods.pptx
Lecture_4_Static_variables_and_Methods.pptx
IkaDeviPerwitasari1
 
Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry Level
Ramrao Desai
 
Pi j2.3 objects
Pi j2.3 objectsPi j2.3 objects
Pi j2.3 objects
mcollison
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
BG Java EE Course
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptx
chetanpatilcp783
 
Ch. 6 -Static Class Members.ppt programming
Ch. 6 -Static Class Members.ppt programmingCh. 6 -Static Class Members.ppt programming
Ch. 6 -Static Class Members.ppt programming
adamjarrah2006
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword ppt
Vinod Kumar
 
Class and Object.pptx from nit patna ece department
Class and Object.pptx from nit patna ece departmentClass and Object.pptx from nit patna ece department
Class and Object.pptx from nit patna ece department
om2348023vats
 
Session 3 Constructors, Types, Overloading, Static MethodsNotes.pdf
Session 3 Constructors, Types, Overloading, Static MethodsNotes.pdfSession 3 Constructors, Types, Overloading, Static MethodsNotes.pdf
Session 3 Constructors, Types, Overloading, Static MethodsNotes.pdf
tabbu23
 
Class and Object JAVA PROGRAMMING LANG .pdf
Class and Object JAVA PROGRAMMING LANG .pdfClass and Object JAVA PROGRAMMING LANG .pdf
Class and Object JAVA PROGRAMMING LANG .pdf
sameer2543ynr
 
03_Objects and Classes in java.pdf
03_Objects and Classes in java.pdf03_Objects and Classes in java.pdf
03_Objects and Classes in java.pdf
Parameshwar Maddela
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Tushar B Kute
 
Ad

More from Shalabh Chaudhary (15)

Everything about Zoho Workplace
Everything about Zoho WorkplaceEverything about Zoho Workplace
Everything about Zoho Workplace
Shalabh Chaudhary
 
C Pointers & File Handling
C Pointers & File HandlingC Pointers & File Handling
C Pointers & File Handling
Shalabh Chaudhary
 
C MCQ & Basic Coding
C MCQ & Basic CodingC MCQ & Basic Coding
C MCQ & Basic Coding
Shalabh Chaudhary
 
Database Management System [DBMS]
Database Management System [DBMS]Database Management System [DBMS]
Database Management System [DBMS]
Shalabh Chaudhary
 
PL-SQL, Cursors & Triggers
PL-SQL, Cursors & TriggersPL-SQL, Cursors & Triggers
PL-SQL, Cursors & Triggers
Shalabh Chaudhary
 
Soft Computing [NN,Fuzzy,GA] Notes
Soft Computing [NN,Fuzzy,GA] NotesSoft Computing [NN,Fuzzy,GA] Notes
Soft Computing [NN,Fuzzy,GA] Notes
Shalabh Chaudhary
 
Software Engineering (SE) Notes
Software Engineering (SE) NotesSoftware Engineering (SE) Notes
Software Engineering (SE) Notes
Shalabh Chaudhary
 
Operating System (OS) Notes
Operating System (OS) NotesOperating System (OS) Notes
Operating System (OS) Notes
Shalabh Chaudhary
 
Data Communication & Networking Notes
Data Communication & Networking NotesData Communication & Networking Notes
Data Communication & Networking Notes
Shalabh Chaudhary
 
Java Basics for Interview
Java Basics for InterviewJava Basics for Interview
Java Basics for Interview
Shalabh Chaudhary
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
Shalabh Chaudhary
 
Java Fundamentals
Java FundamentalsJava Fundamentals
Java Fundamentals
Shalabh Chaudhary
 
Unified Modeling Language(UML) Notes
Unified Modeling Language(UML) NotesUnified Modeling Language(UML) Notes
Unified Modeling Language(UML) Notes
Shalabh Chaudhary
 
Advanced JAVA Notes
Advanced JAVA NotesAdvanced JAVA Notes
Advanced JAVA Notes
Shalabh Chaudhary
 
Core JAVA Notes
Core JAVA NotesCore JAVA Notes
Core JAVA Notes
Shalabh Chaudhary
 
Ad

Recently uploaded (20)

Structural Health and Factors affecting.pptx
Structural Health and Factors affecting.pptxStructural Health and Factors affecting.pptx
Structural Health and Factors affecting.pptx
gunjalsachin
 
Electrical and Electronics Engineering: An International Journal (ELELIJ)
Electrical and Electronics Engineering: An International Journal (ELELIJ)Electrical and Electronics Engineering: An International Journal (ELELIJ)
Electrical and Electronics Engineering: An International Journal (ELELIJ)
elelijjournal653
 
Tesia Dobrydnia - A Leader In Her Industry
Tesia Dobrydnia - A Leader In Her IndustryTesia Dobrydnia - A Leader In Her Industry
Tesia Dobrydnia - A Leader In Her Industry
Tesia Dobrydnia
 
Highway Engineering - Pavement materials
Highway Engineering - Pavement materialsHighway Engineering - Pavement materials
Highway Engineering - Pavement materials
AmrutaBhosale9
 
ISO 4548-7 Filter Vibration Fatigue Test Rig Catalogue.pdf
ISO 4548-7 Filter Vibration Fatigue Test Rig Catalogue.pdfISO 4548-7 Filter Vibration Fatigue Test Rig Catalogue.pdf
ISO 4548-7 Filter Vibration Fatigue Test Rig Catalogue.pdf
FILTRATION ENGINEERING & CUNSULTANT
 
"The Enigmas of the Riemann Hypothesis" by Julio Chai
"The Enigmas of the Riemann Hypothesis" by Julio Chai"The Enigmas of the Riemann Hypothesis" by Julio Chai
"The Enigmas of the Riemann Hypothesis" by Julio Chai
Julio Chai
 
UNIT-4-PPT UNIT COMMITMENT AND ECONOMIC DISPATCH
UNIT-4-PPT UNIT COMMITMENT AND ECONOMIC DISPATCHUNIT-4-PPT UNIT COMMITMENT AND ECONOMIC DISPATCH
UNIT-4-PPT UNIT COMMITMENT AND ECONOMIC DISPATCH
Sridhar191373
 
Software Engineering Project Presentation Tanisha Tasnuva
Software Engineering Project Presentation Tanisha TasnuvaSoftware Engineering Project Presentation Tanisha Tasnuva
Software Engineering Project Presentation Tanisha Tasnuva
tanishatasnuva76
 
UNIT-5-PPT Computer Control Power of Power System
UNIT-5-PPT Computer Control Power of Power SystemUNIT-5-PPT Computer Control Power of Power System
UNIT-5-PPT Computer Control Power of Power System
Sridhar191373
 
[HIFLUX] Lok Fitting&Valve Catalog 2025 (Eng)
[HIFLUX] Lok Fitting&Valve Catalog 2025 (Eng)[HIFLUX] Lok Fitting&Valve Catalog 2025 (Eng)
[HIFLUX] Lok Fitting&Valve Catalog 2025 (Eng)
하이플럭스 / HIFLUX Co., Ltd.
 
Axial Capacity Estimation of FRP-strengthened Corroded Concrete Columns
Axial Capacity Estimation of FRP-strengthened Corroded Concrete ColumnsAxial Capacity Estimation of FRP-strengthened Corroded Concrete Columns
Axial Capacity Estimation of FRP-strengthened Corroded Concrete Columns
Journal of Soft Computing in Civil Engineering
 
ISO 5011 Air Filter Catalogues .pdf
ISO 5011 Air Filter Catalogues      .pdfISO 5011 Air Filter Catalogues      .pdf
ISO 5011 Air Filter Catalogues .pdf
FILTRATION ENGINEERING & CUNSULTANT
 
Influence line diagram in a robust model
Influence line diagram in a robust modelInfluence line diagram in a robust model
Influence line diagram in a robust model
ParthaSengupta26
 
Kevin Corke Spouse Revealed A Deep Dive Into His Private Life.pdf
Kevin Corke Spouse Revealed A Deep Dive Into His Private Life.pdfKevin Corke Spouse Revealed A Deep Dive Into His Private Life.pdf
Kevin Corke Spouse Revealed A Deep Dive Into His Private Life.pdf
Medicoz Clinic
 
May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...
May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...
May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...
gerogepatton
 
Numerical Investigation of the Aerodynamic Characteristics for a Darrieus H-t...
Numerical Investigation of the Aerodynamic Characteristics for a Darrieus H-t...Numerical Investigation of the Aerodynamic Characteristics for a Darrieus H-t...
Numerical Investigation of the Aerodynamic Characteristics for a Darrieus H-t...
Mohamed905031
 
Digital Crime – Substantive Criminal Law – General Conditions – Offenses – In...
Digital Crime – Substantive Criminal Law – General Conditions – Offenses – In...Digital Crime – Substantive Criminal Law – General Conditions – Offenses – In...
Digital Crime – Substantive Criminal Law – General Conditions – Offenses – In...
ManiMaran230751
 
Android basics – Key Codes – ADB – Rooting Android – Boot Process – File Syst...
Android basics – Key Codes – ADB – Rooting Android – Boot Process – File Syst...Android basics – Key Codes – ADB – Rooting Android – Boot Process – File Syst...
Android basics – Key Codes – ADB – Rooting Android – Boot Process – File Syst...
ManiMaran230751
 
Pruebas y Solucion de problemas empresariales en redes de Fibra Optica
Pruebas y Solucion de problemas empresariales en redes de Fibra OpticaPruebas y Solucion de problemas empresariales en redes de Fibra Optica
Pruebas y Solucion de problemas empresariales en redes de Fibra Optica
OmarAlfredoDelCastil
 
Structural Health and Factors affecting.pptx
Structural Health and Factors affecting.pptxStructural Health and Factors affecting.pptx
Structural Health and Factors affecting.pptx
gunjalsachin
 
Electrical and Electronics Engineering: An International Journal (ELELIJ)
Electrical and Electronics Engineering: An International Journal (ELELIJ)Electrical and Electronics Engineering: An International Journal (ELELIJ)
Electrical and Electronics Engineering: An International Journal (ELELIJ)
elelijjournal653
 
Tesia Dobrydnia - A Leader In Her Industry
Tesia Dobrydnia - A Leader In Her IndustryTesia Dobrydnia - A Leader In Her Industry
Tesia Dobrydnia - A Leader In Her Industry
Tesia Dobrydnia
 
Highway Engineering - Pavement materials
Highway Engineering - Pavement materialsHighway Engineering - Pavement materials
Highway Engineering - Pavement materials
AmrutaBhosale9
 
"The Enigmas of the Riemann Hypothesis" by Julio Chai
"The Enigmas of the Riemann Hypothesis" by Julio Chai"The Enigmas of the Riemann Hypothesis" by Julio Chai
"The Enigmas of the Riemann Hypothesis" by Julio Chai
Julio Chai
 
UNIT-4-PPT UNIT COMMITMENT AND ECONOMIC DISPATCH
UNIT-4-PPT UNIT COMMITMENT AND ECONOMIC DISPATCHUNIT-4-PPT UNIT COMMITMENT AND ECONOMIC DISPATCH
UNIT-4-PPT UNIT COMMITMENT AND ECONOMIC DISPATCH
Sridhar191373
 
Software Engineering Project Presentation Tanisha Tasnuva
Software Engineering Project Presentation Tanisha TasnuvaSoftware Engineering Project Presentation Tanisha Tasnuva
Software Engineering Project Presentation Tanisha Tasnuva
tanishatasnuva76
 
UNIT-5-PPT Computer Control Power of Power System
UNIT-5-PPT Computer Control Power of Power SystemUNIT-5-PPT Computer Control Power of Power System
UNIT-5-PPT Computer Control Power of Power System
Sridhar191373
 
Influence line diagram in a robust model
Influence line diagram in a robust modelInfluence line diagram in a robust model
Influence line diagram in a robust model
ParthaSengupta26
 
Kevin Corke Spouse Revealed A Deep Dive Into His Private Life.pdf
Kevin Corke Spouse Revealed A Deep Dive Into His Private Life.pdfKevin Corke Spouse Revealed A Deep Dive Into His Private Life.pdf
Kevin Corke Spouse Revealed A Deep Dive Into His Private Life.pdf
Medicoz Clinic
 
May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...
May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...
May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...
gerogepatton
 
Numerical Investigation of the Aerodynamic Characteristics for a Darrieus H-t...
Numerical Investigation of the Aerodynamic Characteristics for a Darrieus H-t...Numerical Investigation of the Aerodynamic Characteristics for a Darrieus H-t...
Numerical Investigation of the Aerodynamic Characteristics for a Darrieus H-t...
Mohamed905031
 
Digital Crime – Substantive Criminal Law – General Conditions – Offenses – In...
Digital Crime – Substantive Criminal Law – General Conditions – Offenses – In...Digital Crime – Substantive Criminal Law – General Conditions – Offenses – In...
Digital Crime – Substantive Criminal Law – General Conditions – Offenses – In...
ManiMaran230751
 
Android basics – Key Codes – ADB – Rooting Android – Boot Process – File Syst...
Android basics – Key Codes – ADB – Rooting Android – Boot Process – File Syst...Android basics – Key Codes – ADB – Rooting Android – Boot Process – File Syst...
Android basics – Key Codes – ADB – Rooting Android – Boot Process – File Syst...
ManiMaran230751
 
Pruebas y Solucion de problemas empresariales en redes de Fibra Optica
Pruebas y Solucion de problemas empresariales en redes de Fibra OpticaPruebas y Solucion de problemas empresariales en redes de Fibra Optica
Pruebas y Solucion de problemas empresariales en redes de Fibra Optica
OmarAlfredoDelCastil
 

OOPs & Inheritance Notes

  • 1. By- Shalabh Chaudhary [GLAU] OOPs + INHERITANCE OOP  Object Oriented Programming is a programming paradigm which uses "Objects" consisting of data fields and methods together with their interactions. Classes and Objects   A class contains variable declarations and method definitions.  Variable declared inside method – Local Variable.  Variable declared inside class & outside method – Instance Variable.  Variables with method declarations - parameters or arguments. Mthd(int var/arg){}.  Class Variable – Can be static.  Local Variable – Can’t be static. Objects and References   All other types, except 8 primitive data type, refers to objects.  Variables that refers to objects are reference variables.  Once class is defined, you can declare a variable(object reference) of type class. Student stud1; Employee emp1; NOTE: Both stud1 and emp1 are objects or reference var but not object of Student/Employee class, it only holds reference of new object created.  The new operator is used to create an object of that reference type Employee emp = new Employee(); // Employee() – object.  Object references are used to store objects.  The new operator,  Dynamically allocates memory for an object  Creates the object on the heap  Returns a reference to it - The reference is then stored in the variable. Constructors  Constructor is automatically invoked whenever an object of the class is created. Used to initialize instance variables.  Rules to Define Constructor -  A constructor has the same name as the class name.  Should not have a return type.  Can be defined with any access specifier (like private, public).  A class can contain more than one constructor, So it can be overloaded.
  • 2. By- Shalabh Chaudhary [GLAU]  Eg.: public class Sample { private int id; Sample() { id = 101; System.out.println("Default constructor,with ID: "+id); } Sample(int no){ id = no; System.out.println("One arg constructor,withID: "+ id); } } public class ConstDemo{ public static void main(String[] args) { Sample s1 = new Sample(); Sample s2 = new Sample(102); } } Output - Default constructor,with ID: 101 One argument constructor,with ID: 102 this reference keyword  Each class member funct contains an implicit reference of its class type, named this.  this reference is created automatically by compiler.  It contains the address of the object through which the function is invoked.  Use of this keyword.  To refer instance var when there is clash with local var or method arguments.  Used to call overloaded constructors from another constructor of same class.  Use this.variableName to explicitly refer to instance variable.  The this reference is implicitly used to refer to instance variables and methods.  It CANNOT be used in a static method.  Ex1: void setId(intid) { this.id = id; }  Ex2: class Sample{ Sample(){ this("Java"); // calls overloaded constructor System.out.println("Default constructor "); } Sample(String str){ System.out.println("One argument constructor "+ str); } }
  • 3. By- Shalabh Chaudhary [GLAU] Static Class Members Static class members are members of class that don’t belong to instance of a class.  We can access static members directly by prefixing the members with class name ClassName.staticVariable ClassName.staticMethod(...) Static variables:  Shared among all objects of the class.  Only one copy exists for the entire class to use. Static methods :  Static methods can only access directly the static members and manipulate a class’s static variables.  Static methods cannot access non-static members(instance variables or instance methods) of the class.  Static method can’t access this and super references.  Eg.: class StaticDemo { private static inta = 0; private int b; public void set ( int i, int j) { a = i; b = j; } public void show() { System.out.println("This is static a: " + a ); System.out.println( "This is non-static b: " + b ); } public static void main(String args[]) { StaticDemox = new StaticDemo(); StaticDemoy = new StaticDemo(); x.set(1,1); x.show(); y.set(2,2); y.sow(); x.show(); } } Output: This is static a: 1 This is non-static b: 1 This is static a: 2 This is non-static b: 2 This is static a: 2 This is non-static b: 1 QQ. Why is main() method static ?
  • 4. By- Shalabh Chaudhary [GLAU] OUTPUT BASED   class Sample{ int i_val; public static void main(String[] xyz){ System.out.println("i_val is :"+ this.i_val); } } >> Error: non-static variable this cannot be referenced from a static context  class Sample { int i_val=10; Sample(int i_val){ this.i_val=i_val; System.out.println("inside Sample i_val: "+this.i_val); } public static void main(String[] xyz){ Sample o = new Sample(); } } >> Error: No default constructor created. “static” Block  A block of code enclosed in braces, preceded by the keyword static. Eg.: static { System.out.println(“Within static block”); }  The statements within the static block are executed automatically when the class is loaded into JVM.  They are executed in the order of their appearance in the class.  JVM combines all static blocks in a class as single static block and executes them.  class Sample{ public static void main(String[] xyz){ System.out.println("Inside main method line1"); } static { System.out.println("Inside class line1"); } } >> Inside class line1 Inside main method line1
  • 5. By- Shalabh Chaudhary [GLAU] ***Create object of First class in Second class using new opr & run Second class print something.  public class DefaultConstruct { String name; int roll; void detail() { System.out.println(name); // initialize null by default. System.out.println(roll); // initialize to 0 by default. } public static void main(String[] args) { DefaultConstruct d = new DefaultConstruct(); d.detail(); } } // >> constructor not defined then default constructor is created. // >> Default constructor has no parameter it initializes instance var to default values. // >> // Can Define Constructor like – DefaultConstruct (){ initialize values; } Constructor v/s Method   Doesn’t have return type but Method has return type.  Called using new operator & Method called using (.) operator.  By default Method return type is private. #1. Create a class Box that uses a parameterized method to initialize the dimensions of a box.(dimensions are width, height, depth of double type). The class should have a method that can return volume. Obtain an object and print the corresponding volume in main() function. >> Run as BoxVol.java import java.util.Scanner; class Box{ double width,height,depth; // Instance Variables Box(double w,double h,double d) { // Constructor width=w; height=h;
  • 6. By- Shalabh Chaudhary [GLAU] depth=d; } double volume() { // Method-Volume return width*depth*height; } } public class BoxVol { // Main Class public static void main(String[] args) { Scanner scan=new Scanner(System.in); double w=scan.nextInt(); double h=scan.nextInt(); double d=scan.nextInt(); Box b= new Box(w,h,d); System.out.println("Volume is:"+b.volume()); } } #2. Create a new class called “Calculator” which contains the following: 1. A static method called powerInt(int num1,int num2) that accepts two integers and returns num1 to the power of num2 (num1 power num2). 2. A static method called powerDouble(double num1,int num2) that accepts one double and one integer and returns num1 to the power of num2 (num1 power num2). 3. Call your method from another class without instantiating the class (i.e. call it like Calculator.powerInt(12,10) since your methods are defined to be static) Hint: Use Math.pow(double,double) to calculate the power. >> Run As CalcPower.java class Calculator{ static double powerInt(int num1,int num2) { return Math.pow(num1,num2);
  • 7. By- Shalabh Chaudhary [GLAU] } static double powerDouble(double num1,int num2) { return Math.pow(num1,num2); } } public class CalcPower { public static void main(String[] args) { System.out.println(Calculator.powerInt(12,10)); System.out.println(Calculator.powerDouble(12.5,10)); } } #3. Design a class that can be used by a health care professional to keep track of a patient’s vital statistics. Here’s what the class should do: 1. Construct a class called Patient 2. Store a String name for the patient 3. Store weight and height for patient as doubles 4. Construct a new patient using these values 5. Write a method called BMI which returns the patient’s BMI as a double. BMI can be calculated as BMI = ( Weight in Pounds / ( Height in inches x Height in inches ) ) x 703 6. Next, construct a class called “Patients” and create a main method. Create a Patient object and assign some height and weight to that object. Display the BMI of that patient. >> Run as Patients.java class Patient { String name; double weight,height; Patient(double w,double h){
  • 8. By- Shalabh Chaudhary [GLAU] weight=w; height=h; } double BMI() { return (weight/(height*height))*703; } } public class Patients{ public static void main(String[] args) { Patient p=new Patient(75,156); System.out.println("BMI is:"+p.BMI()); } } Encapsulation & Abstraction   Encapsulation = hiding implementation level details.  Abstraction = exposing only interface. Access Specifiers   Access specifiers help implement:  Encapsulation by hiding implementation-level details in a class.  Abstraction by exposing only the interface of the class to the external world.  Implementation of Encapsulation & Abstraction - class Point { private int x; private int y; void setX( int x) { x = (x > 79 ? 79 : (x < 0 ? 0 :x)); // this.x= } void setY(int y) { y = (y > 24 ? 24 : (y < 0 ? 0 : y)); // this.y= } int getX()
  • 9. By- Shalabh Chaudhary [GLAU] { return x; } int getY() { return y; } } class PointDemo { public static void main(String args[]) { int a, b; Point p = new Point(); p.setX(22); p.setY(44); System.out.println("The value of a is "+p.getX()); System.out.println("The value of b is "+p.getY()); } } >> Output: The value of a is 0 The value of b is 0 Use this.x & this.y in setX and setY mthd to get 22,44 as o/p. #1. Create a class called Author is designed as follows: It contains: • Three private instance variables: name (String), email (String), and gender (char of either ‘m’ or ‘f’). • One constructor to initialize the name, email and gender with the given values. And, a class called Book is designed as follows: It contains: • Four private instance variables: name (String), author (of the class Author you have just created), price (double), and qtyInStock (int). Assuming that each book is written by one author. • One constructor which constructs an instance with the values given. • Getters and setters: getName(), getAuthor(), getPrice(), setPrice(), getQtyInStock(), setQtyInStock(). Again there is no setter for name and author. Write the class Book (which uses the Author class written earlier). Try:
  • 10. By- Shalabh Chaudhary [GLAU] 1. Printing the book name, price and qtyInStock from a Book instance. (Hint: aBook.getName()) 2. After obtaining the “Author” object, print the Author (name, email & gender) of the book. >> class Author { public static String name,email; public static char gender; Author(String n,String e, char g){ name=n; email=e; gender=g; } } class Book{ String name1,author; double price; int qtyInStock; Book(String n1){ name1=n1; } void setQtyInStock() { qtyInStock=10; } void setPrice() { price=100.0; } double getPrice() { return price; }
  • 11. By- Shalabh Chaudhary [GLAU] int getQtyInStock() { return qtyInStock; } String getName() { return name1; } void getAuthor() { System.out.println("Author is:"+Author.name); System.out.println("Mail id is:"+Author.email); System.out.println("Gender is:"+Author.gender); } } public class Books{ public static void main(String args[]) { Book b=new Book("Computer Networks"); Author a=new Author("amy","[email protected]",'f'); b.setPrice(); b.setQtyInStock(); System.out.println("The name of the book is :"+b.getName()); System.out.println("The price of the book is :"+b.getPrice()); System.out.println("The stock is :"+b.getQtyInStock()); b.getAuthor(); } }
  • 12. By- Shalabh Chaudhary [GLAU] Inheritance  It allows for the creation of hierarchical classifications.  Each of these classes will add only those attributes & behaviors that are unique to it.  Super Class = class that is inherited. [ Base Class / Parent Class ]  Sub Class = class that does the inheriting. [ Derived Class / Extended Class / child class ]  Sub class inherits all properties of its superclass. Basic building blocks of OOPs   Association = Relationship between two objects.  The association could be - 1. one-to-one 2. one-to-many 3. many-to-one 4. many-to-many  Types of Association –  Aggregation = A directional association between objects. Also called a “Has-a” relationship. Example: College has a Student Object.  Composition [Restricted Aggregation] = When an object contains other object, if contained obj. can’t exist without existence of container obj, => compos Example: A class contains students. >> Student can’t exist without class.There exists composition b/w class & students.  Containership = Means using instance variables that refer to other objects. Inheritance Model  Java uses Single inheritance model. Single Inheritance  In single inheritance, a subclass can inherit from one(and only one) super class. Syntax: class derived-class-name extends base-class-name { //code goes here } Eg.:  class A { int m, n; void display1( ) { System.out.println("m and n are:"+m+" "+n); } } class B extends A { int c; void display2() { System.out.println("c :"+ c); } void sum() { System.out.println("m+n+c= "+ (m+n+c)); } } class Main {
  • 13. By- Shalabh Chaudhary [GLAU] public static void main(String args[ ]) { A s1= new A(); // creating objects B s2= new B(); s1.m= 10; s1.n= 20; System.out.println("State of object A:"); s1.display1(); s2.m= 7; s2.n= 8; s2.c= 9; System.out.println("State of object B:"); s2.display1(); s2.display2(); System.out.println("sum of m, n and c in object B is:"); s2.sum(); } }  Accessing Superclass Members from a Subclass Object   A sub class includes all of the members of its super class. But, it cannot directly access those members of the super class that have been declared as private. Eg.: class A { int money; private int pocketMoney; void fill(int money,int pocketMoney) { this.money=money; this.pocketMoney= pocketMoney; } } class B extends A { int total; void sum( ) { total = money + pocketMoney; } } class AccessDemo { public static void main(String args[ ]) { B subob= new B(); subob.fill(10,12); subob.sum(); System.out.println("Total: " + subob.total); } }
  • 14. By- Shalabh Chaudhary [GLAU] Using super   When a subclass object is created, It creates the super class object.  The constructors of the super class are never inherited by the subclass.  super keyword is used -> 1. To differentiate the members of superclass from the members of subclass, if they have same names. 2. To invoke the superclass constructor from subclass.  Eg.: package mypack; class Employee{ int Employeeno; String Empname; Employee() { System.out.println(" Employee No-argConstructor Begins"); Employeeno=0; Empname= null; System.out.println(" Employee No-argConstructor Ends"); } Employee(int Employeeno) { System.out.println(" Employee 1-arg Constructor Begins"); this.Employeeno=Employeeno; this.Empname= "UNKNOWN"; System.out.println(" Employee 1-arg Constructor Ends"); } Employee(int Employeeno, String s) { System.out.println(" Employee 2-arg Constr Begins"); this.Employeeno= Employeeno; this.Empname= s;System.out.println("Emp 2-arg Constr Ends"); } void display(){ System.out.println(" Employee Number = "+Employeeno); System.out.println(" Employee Name = "+Empname); } } class Manager extends Employee { String deptname; Manager(int Employeeno, String name, String deptname){ super(Employeeno, name); System.out.println(" Manager 3-arg Constr Begins"); this.deptname= deptname; System.out.println(" Manager 3-arg Construct Ends"); } void display(){ super.display(); System.out.println(" Deptname= "+deptname); }
  • 15. By- Shalabh Chaudhary [GLAU] public static void main( String a[]) { System.out.println(" [Main function Begins---] "); System.out.println("Creating object for manager class"); Manager mm = new Manager(10,"Gandhi","Banking"); System.out.println(" Printintthe manager details: "); mm.display(); System.out.println(" [Main function Ends----]"); } } Using super to Call Superclass Constructors  super() - Always be the first statement executed inside a subclass constructor. - Tells order of invocation of constructors in a class hierarchy.  Constructors in a class hierarchy are invoked in the order of their derivation. Using this() in a constructor   this(arg_ list) stmt invokes the constructor of the same class.  First line of a constructor must EITHER be a super(call on the super class constructor) OR a this(call on the constructor of same class).  If the first statement within a constructor is NEITHER super() NOR this(), then compiler will automatically insert a super(). [ i.e., invocation to the super class no argument constructor]. OUTPUT BASED   class A1 { A1() { System.out.println("A1's no arg constructor"); } A1(int a) { System.out.println("A1's constructor "+ a); } } class B1 extends A1 { B1(){ System.out.println("B1's no arg constructor"); } B1(int b){ super(1000); System.out.println("B1's constructor "+ b); } } class C1 extends B1{ C1() {
  • 16. By- Shalabh Chaudhary [GLAU] System.out.println("C1's no arg constructor"); } C1(int c){ super(100); System.out.println("C1's constructor "+ c); } } class TestingInheritance{ public static void main(String args[]){ C1 ca = new C1(); } } >> Output: A1's no arg constructor B1's no arg constructor C1's no arg constructor  class A1 { A1(){ System.out.println("A1's no arg constructor"); } A1(int a) { System.out.println("A1's constructor "+ a); } } class B1 extends A1{ B1(){ System.out.println("B1's no arg constructor"); } B1(int b){ super(1000); System.out.println("B1's constructor "+ b); } } class C1 extends B1{ C1() { System.out.println("C1's no arg constructor"); } C1(int c){ super(100); System.out.println("C1's constructor "+ c); } } class TestingInheritance { public static void main(String args[]){ C1 ca = new C1(10);
  • 17. By- Shalabh Chaudhary [GLAU] } } >> Output: A1's constructor 1000 B1's constructor 100 C1's constructor 10  class A1 { A1(){ System.out.println("A1's no arg constructor"); } A1(int a){ System.out.println("A1's constructor "+ a); } } class B1 extends A1{ B1(){ System.out.println("B1's no arg constructor"); } B1(int b){ super(1000); System.out.println("B1‘s constructor "+ b); } } class C1 extends B1{ C1() { System.out.println("C1's no arg constructor"); } C1(int c){ System.out.println("C1's constructor "+ c); } } class TestingInheritance{ public static void main(String args[]){ C1 ca = new C1(10); } } >> Output- A1's no arg constructor B1's no arg constructor C1's constructor 10  class A1 { A1(){ System.out.println("A1's no arg constructor"); } A1(int a){
  • 18. By- Shalabh Chaudhary [GLAU] System.out.println("A1's constructor "+ a); } } class B1 extends A1{ B1(){ System.out.println("B1's no arg constructor"); } B1(int b){ System.out.println("B1‘s constructor "+ b); } } class C1 extends B1{ C1() { super(100);System.out.println("C1's no arg constructor"); } C1(int c){ System.out.println("C1's constructor "+ c); } } class TestingInheritance{ public static void main(String args[]){ C1 ca = new C1(10); } } >> Output: A1's no arg constructor B1's no arg constructor C1's constructor 10  class A1 { A1(){ System.out.println("A1's no arg constructor"); } A1(int a){ System.out.println("A1's constructor "+ a); } } class B1 extends A1{ B1(){ super(50); System.out.println("B1's no arg constructor"); } B1(int b){ super(1000); System.out.println("B1‘s constructor "+ b); }
  • 19. By- Shalabh Chaudhary [GLAU] } class C1 extends B1{ C1() { System.out.println("C1's no arg constructor"); } C1(int c){ System.out.println("C1's constructor "+ c); } } class TestingInheritance{ public static void main(String args[]){ C1 ca = new C1(10); } } >> Output- A1's constructor 50 B1's no arg constructor C1's constructor 10  class A1 { A1(){ System.out.println("A1's no arg constructor"); } A1(int a){ System.out.println("A1's constructor "+ a); } } class B1 extends A1{ B1(){ System.out.println("B1's no arg constructor"); } B1(int b){ this("x"); System.out.println("B1's constructor "+ b); } B1(String b){ super(1000); System.out.println("B1's constructor "+ b); } } class C1 extends B1{ C1() { System.out.println("C1's no arg constructor"); } C1(int c){ super(100); System.out.println("C1's constructor "+ c);
  • 20. By- Shalabh Chaudhary [GLAU] } } class TestingInheritance { public static void main(String args[]){ C1 ca = new C1(10); } } >> Output: A1's constructor 1000 B1's constructor x B1's constructor 100 C1's constructor 10 Multilevel Hierarchy  A derived class will be inheriting a base class and as well as the derived class also act as the base class to other class.  class student { int rollno; String name; student(int r, String n) { rollno = r; name = n; } void dispdatas() { System.out.println("Rollno = " + rollno); System.out.println("Name = " + name); } } class marks extends student { int total; marks(int r, String n, int t) { super(r,n); //call super class (student) constructor total = t; }
  • 21. By- Shalabh Chaudhary [GLAU] void dispdatam() { dispdatas(); // call dispdatap of student class System.out.println("Total = " + total); } } class percentage extends marks { int per; percentage(int r, String n, int t, int p) { super(r,n,t); //call super class(marks) constructor per = p; } void dispdatap() { dispdatam(); // call dispdatap of marks class System.out.println("Percentage = " + per); } } class Multi_Inhe { public static void main(String args[]) { percentage stu = new percentage(102689, "VINEETH", 350, 70); //call constructor percentage stu.dispdatap(); // call dispdatap of percentage class } }
  • 22. By- Shalabh Chaudhary [GLAU] Hierarchical Inheritance  one class serves as a superclass (base class) for more than one sub class.In below image, the class A serves as a base class for the derived class B,C and D.  class A { public void methodA() { System.out.println("Class A Mthd"); } } class B extends A { public void methodB(){ System.out.println("Class B Mthd"); } } class C extends A { public void methodC() { System.out.println("method of Class C"); } } class D extends A { public void methodD() { System.out.println("method of Class D"); } } class HierarchInheritance { public static void main(String args[]) { B obj1 = new B(); C obj2 = new C(); D obj3 = new D(); //All classes can access the method of class A obj1.methodA(); obj2.methodA(); obj3.methodA(); } } Java does NOT Support Multiple Inheritance with classes.
  • 23. By- Shalabh Chaudhary [GLAU] Multiple Inheritance [Through Interfaces]  One class can have more than one superclass and inherit features from all parent classes.  interface PI1 { // default method default void show() { System.out.println("Default PI1"); } } interface PI2 { // Default method default void show() { System.out.println("Default PI2"); } } // Implementation class code class TestClass implements PI1, PI2 { // Overriding default show method public void show() { // use super keyword to call the show // method of PI1 interface PI1.super.show(); // use super keyword to call the show // method of PI2 interface PI2.super.show(); } public static void main(String args[]) { TestClass d = new TestClass(); d.show(); } } Hybrid Inheritance [Through Interfaces]  It is a mix of two or more of the above types of inheritance.  public class ClassA { public void dispA(){ System.out.println("Class A Mthd"); } } public interface InterfaceB { public void show(); }
  • 24. By- Shalabh Chaudhary [GLAU] public interface InterfaceC { public void show(); } public class ClassD implements InterfaceB,InterfaceC { public void show() { System.out.println("show() method implementation"); } public void dispD() { System.out.println("disp() method of ClassD"); } public static void main(String args[]) { ClassD d = new ClassD(); d.dispD(); d.show(); } } #1. Create a class named ‘Animal’ which includes methods like eat() and sleep(). Create a child class of Animal named ‘Bird’ and override the parent class methods. Add a new method named fly(). Create an instance of Animal class and invoke the eat and sleep methods using this object. Create an instance of Bird class and invoke the eat, sleep and fly methods using this object. >> class Animal { void eat() { System.out.println("eat Mthd"); } void sleep() { System.out.println("sleep Mthd"); } } class Bird extends Animal{ @Override void eat() { System.out.println("Override eat Mthd");
  • 25. By- Shalabh Chaudhary [GLAU] } void sleep() { System.out.println("Override sleep Mthd"); } void fly() { System.out.println("fly method"); } } class AnimalsDemo{ public static void main(String args[]) { Animal a = new Animal(); Bird b= new Bird(); a.eat(); a.sleep(); b.eat(); b.sleep(); b.fly(); } } #2. Create class called Person with a member variable name. Save it in file called Person.java Create a class called Employee who will inherit the Person class.The other data members of the employee class are annual salary (double), the year the employee started to work, and the national insurance number which is a String. Save this in a file called Employee.java Your class should have a reasonable number of constructors and accessor methods. Write another class called TestEmployee, containing a main method to fully test your class definition. >> Person.java public class Person { private String name;
  • 26. By- Shalabh Chaudhary [GLAU] public Person(String n){ name=n; } public void setName(String n) { name=n; } public String getName() { return name; } public String toString(){ return name; } } ----x----x----x---- Employee.java public class Employee extends Person { private double annual_salary; private int emp_yr; private String insurance_no; public Employee(String n,double a, int y, String i){ super(n); annual_salary=a; emp_yr=y; insurance_no=i; } public void setSalary(double a) { annual_salary=a; } public void setYear(int y) {
  • 27. By- Shalabh Chaudhary [GLAU] emp_yr=y; } public void setInsurance_no(String i) { insurance_no=i; } public double getSalary() { return annual_salary; } public int getYear() { return emp_yr; } public String getInsurance_no() { return insurance_no; } public String toString() { return super.toString()+" "+annual_salary+" "+emp_yr+" "+insurance_no; } } ----x----x----x---- TestEmployee.java public class TestEmployee { public static void main(String[] args) { Person p= new Person("Anil"); Employee e=new Employee("Jim",10000, 2015, "abcd"); System.out.println(p); System.out.println(e); } }
  • 28. By- Shalabh Chaudhary [GLAU] Method Overriding [ Polymorphism ]  When a method in a subclass has the same prototype as a method in the superclass, then the method in the subclass is said to override the method in the super class.  Same prototype - Means has the same name, type signature (the same type, sequence and number of parameters), and the same return type as the method in its super class.  class A { int a,b; A(int m, int n) { a = m; b = n; } void display() { System.out.println("a and b are: "+a+" "+b); } } class B extends A { int c; B(int m, int n, int o) { super(m,n); c = o; } void display() { System.out.println("c :" + c); } } class OverrideDemo { public static void main(String args[]) { B subOb= new B(4,5,6); subOb.display(); } } >> Output- c:6 // display() inside B overrides display declared in its superclass, i.e., class A.
  • 29. By- Shalabh Chaudhary [GLAU] Using super to Call an Overridden Method   class A { int a,b; A(int m, int n) { a = m; b = n; } void display() { System.out.println("a and b are :"+a+" "+b); } } class B extends A { int c; B(int m, int n, int o) { super(m,n); c = o; } void display() { super.display(); System.out.println("c :" + c); } } class OverridewithSuper { public static void main(String args[]) { B subOb= new B(4,5,6); subOb.display(); } } >> Output- a and b are: 4 5 c: 6 // Method overriding occurs only when the names and the type signatures of two methods across atleast two classes (i.e., a superclass and a subclass) in a class hierarchy are identical. If they are not, then the two methods are simply overloaded.
  • 30. By- Shalabh Chaudhary [GLAU] Superclass Reference Variable  A reference variable of type superclass can be assigned a reference to any subclass object derived from that super class.  class A1{ } class A2 extends A1{ } class A3 { public static void main(String[]args) { A1 x; A2 z=newA2(); x=new A2(); //valid z=new A1(); //invalid } } Superclass Reference Variable Can Reference a Subclass Object   Method calls in java are resolved dynamically at runtime. Rules for Method Overriding   Must have the same argument list.  Must have the same return type.  Must not have a more restrictive access modifier  May have a less restrictive access modifier  Must not throw new or broader checked exceptions  May throw fewer or narrower checked exceptions or any unchecked exceptions.  Final methods cannot be overridden.  Constructors cannot be overridden. OUTPUT BASED   class A1 { void m1() { System.out.println("In method m1 of A1"); } } class A2 extends A1 { int m1() { return 100; } public static void main(String[] args) { A2 x = new A2(); x.m1(); } } // Error: m1() in A2 cannot override m1() in A1.
  • 31. By- Shalabh Chaudhary [GLAU] QQ. Why Overridden Methods ? Ans: So, that subclass will override the method in superclass. Dynamic Method Dispatch [ Runtime Polymorphism ]   Occurs when the Java language resolves a call to an overridden method at runtime, and, in turn, implements runtime polymorphism.  Mechanism by which a call to an overridden method is resolved at run time, rather than compile time.  Run time polymorphism possible in class hierarchy with the help of its features: 1. Overridden Methods. 2. Super class Reference variables. - Can hold reference to subclass object.  When an overridden method is called through a super class reference, Java determines which method to call based upon the type of the object being referred to at the time the call occurs.  class Figure{ double dimension1; double dimension2; Figure(double x,double y){ dimension1=x; dimension2=y; } double area(){ System.out.println("Area of Figure is undefined"); return 0; } } class Rectangle extends Figure{ Rectangle(double x,double y){ super(x,y); } double area() { //method overriding System.out.print("Area of rectangle is :"); return dimension1 * dimension2; } } class Triangle extends Figure { Triangle(double x, double y) { super(x,y); } double area() { //method overriding System.out.print("Area for triangle is :"); return dimension1 * dimension2 / 2; } } class FindArea { public static void main(String args[]) {
  • 32. By- Shalabh Chaudhary [GLAU] Figure f=new Figure(10,10); Rectangle r= new Rectangle(9,5); Triangle t= new Triangle(10,8); Figure fig; //reference variable fig=r; System.out.println("Area of rect is:"+fig.area()); fig=t; System.out.println("Area of triangle is:"+fig.area()); fig=f; System.out.println(fig.area()); } } instanceof Operator   Use of instance of operator :  Allows to determine the type of an object.  Compares an object with a specified type.  Takes an object and a type and returns true if object belongs to that type & returns false otherwise.  Used to test if an object is an instanceof a class, an instanceof a subclass, or an instanceof a class that implements an interface.  class A { int i, j; } class B extends A { int a, b; } class C extends A { int m, n; } class instanceOf{ public static void main(String args[]) { A a= new A( ); B b= new B( ); C c= new C( ); A ob=b; if (ob instanceof B) System.out.println("ob now refers to B"); else System.out.println("Ob is not instance of B"); if (ob instanceof A) System.out.println("ob is also instance of A"); else System.out.println("Ob is not instance of A"); if (ob instanceof C)
  • 33. By- Shalabh Chaudhary [GLAU] System.out.println("ob now refers to C"); else System.out.println("Ob is not instance of C"); } } The Cosmic Class – The Object Class   Available in java.lang package  Object is superclass of all other classes; i.e., Java’s own classes, as well as user-defined classes.  This means that a reference variable of type Object can refer to an object of any other class. #1. Create a base class Fruit which has name ,taste and size as its attributes. A method called eat() is created which describes the name of the fruit and its taste. Inherit the same in 2 other class Apple and Orange and override the eat() method to represent each fruit taste. >> class Fruit { String name,taste,size; Fruit(String n,String t,String s) { name=n; taste=t; size=s; } void eat() { System.out.println(name+" "+taste); } } class Apple extends Fruit{ Apple(String n, String t, String s) { super(n, t, s); } @Override
  • 34. By- Shalabh Chaudhary [GLAU] void eat() { System.out.println(name+" "+taste); } } class Orange extends Fruit{ Orange(String n, String t, String s) { super(n, t, s); } @Override void eat() { System.out.println(name+" "+taste); } } public class FruitCheck{ public static void main(String args[]) { Apple a= new Apple("Apple","Sweet","Heart"); Orange o=new Orange("Orange","Sour","Round"); a.eat(); o.eat(); } } #2. Write a program to create a class named shape. It should contain 2 methods- draw() and erase() which should print “Drawing Shape” and “Erasing Shape” respectively. For this class we have three sub classes- Circle, Triangle and Square and each class override the parent class functions- draw() & erase(). The draw() method should print “Drawing Circle”, “Drawing Triangle”, “Drawing Square” respectively. The erase() method should print “Erasing Circle”, “Erasing Triangle”, “Erasing Square” respectively.
  • 35. By- Shalabh Chaudhary [GLAU] Create objects of Circle, Triangle and Square in the following way and observe the polymorphic nature of the class by calling draw() and erase() method using each object. Shape c=new Circle(); Shape t=new Triangle(); Shape s=new Square(); >> class Shape { void draw() { System.out.println("Drawing Shape"); } void erase() { System.out.println("Erasing Shape"); } } class Circle extends Shape{ @Override void draw() { System.out.println("Drawing Circle"); } void erase() { System.out.println("Erasing Circle"); } } class Triangle extends Shape{ @Override void draw() { System.out.println("Drawing Triangle"); } void erase() { System.out.println("Erasing Triangle");
  • 36. By- Shalabh Chaudhary [GLAU] } } class Square extends Shape{ @Override void draw() { System.out.println("Drawing Square"); } void erase() { System.out.println("Erasing Square"); } } public class Polymorphism{ public static void main(String args[]) { Shape c=new Circle(); Shape t=new Triangle(); Shape s=new Square(); c.draw(); c.erase(); t.draw(); t.erase(); s.draw(); s.erase(); } }
  • 37. By- Shalabh Chaudhary [GLAU] Garbage Collection   Once the program completes, These objects become garbage...  Java’s Cleanup Mechanism – The Garbage Collector :  Java has its own Garbage Collector  Test test=new Test(); // Obj. test created & memory allocated for this obj.  test=null;  When you execute this, the reference is deleted but the memory occupied by the object is not released.  To release the memory occupied by the ‘test ’object -  Objects on the heap must be deallocated or destroyed, and their memory released for later reallocation.  Java handles object deallocation automatically through garbage collection.  The Garbage Collection is done automatically by JVM.  To manually do the garbage collection, Use method: Runtime rs= Runtime.getRuntime(); rs.gc(); >> gc() method is used to manually run the garbage collection.  The rs.freeMemory() method - Give free memory available in the system. The finalize() Method  Using finalization, can define specific actions that will occur when an object is just about to be reclaimed by the garbage collector.  Inside finalize() method, specify actions that must be performed before object is destroyed.  Java runtime calls this method whenever it’s about to recycle an object of class. Eg.:  public class CounterTest{ public static int count; public CounterTest( ) { count++; } public static void main(String args[ ]) { CounterTest ob1 = new CounterTest( ) ; System.out.println("Number of objects :" + CounterTest.count) ; CounterTest ob2 = new CounterTest( ); Runtime r = Runtime.getRuntime( ); ob1 = null; ob2 = null; r.gc( );
  • 38. By- Shalabh Chaudhary [GLAU] } protected void finalize( ) { System.out.println("Program about to terminate"); CounterTest.count--; System.out.println("Number of objects :" + CounterTest.count) ; } } >> Output: Number of objects: 1 Number of objects: 2 Program about to terminate Number of objects: 1 Program about to terminate Number of objects: 0  The class A3 cannot be subclass of the final class A2.  Cannot override the final method from parent class A1. String and StringBuffer   String is a group of characters.They are objects of type String  Strings are Immutable – Once obj. created CAN’T be changed.  To get changeable strings use the class called StringBuffer.  String and StringBuffer classes are declared as final, So, there CAN NOT be sub classes of these classes.  The default constructor creates an empty string. String s=new String();  Handling Strings: String str = "abc"; // Empty String  String str = ""; Is equivalent to: char data[] = {'a', 'b', 'c'}; >> If data array in the above is modified after the string object str is created, then str remains unchanged.  String Creation using new Keyword: String str1 = new String("abc"); String str2 = new String("abc"); If(str1==str2) // true same  String objects reference are not same.  String class Methods:  str.length() – System.out.println("shalabh".length() ) // Prints 7 or int len = str.length();  str1+str2 operator – Concatenate 2 or more Strings.
  • 39. By- Shalabh Chaudhary [GLAU] System.ot.println(str1+str2); // str1 and str2 are 2 strings.  str.charAt(i) - Retrieve Character in a String. char c = str.charAt(1); // Prints b if str = "abc";  str1.equals(str2) – Returns true if 2 strings are same. or >> str1==str2 – Returns true if both string matched.  str obj. reference is same  str1.equalsIgnoreCase(str2) – Returns true if 2 string are same even case not matched in both strings.  str1.startsWith(str2) – Tests if string start with specified prefix. "January".startsWith("Jan"); // true  str1.endsWith(str2) – Tests if string ends with specified suffix. "December".endsWith("ber"); // true  str1.compaerTo(str2) – Checks string is bigger or smaller. returns -ve integer if str1 < str2 returns +ve integer if str1 > str2 returns 0 if str1 = str2 Eg.: "Hel".compareToIgnoreCase("hello") // Prints -2 (differ by strings) "Hel".compare("hello") // Prints -32 (H to h differ by -32)  str1.indexOf(str2) – Searches for first Occurrence of character or substring. "Hello".indexOf("l") // Prints 2 i.e., 2nd index. returns -1 if character or string not occurs.  str1.indexOf(str2, fromIndex) – Search character ch within string & return index of first occurrence of this character start from pos fromIndex. Eg.: String str="How was your day today?"; str.indexOf('a',6); // Prints 14 (at 14th index a prsnt) str.indexOf("was", 2); // Prints 4 (from 4th index “was” starts)  str1.lastIndexOf(str2) - Searches last occurrence of particular string or character  str1.substring(beginIndex, endIndex) – Returns new string which is substring of string str1 Eg.: "Unhappy".substring(2) // Prints happy. "Smiles".substring(1,5) // Prints mile [ endIndex=5 i.e.,5-1= till 4th ]  str1.concat(str2) – Concatenate specified string(str2) to end of string. "to".concat("get").concat("her") // Prints “together”
  • 40. By- Shalabh Chaudhary [GLAU]  str1.replace(oldChar, newChar) – Return new string - replace oldChar with new "Wipra Technalagies".replace('a', 'o') >> Prints Wipro Technologies.  valueOf(ar) – Convert character array into string. Result is string representation of argument passed as char array.  str1.toLoweCase() - "HELLO WORLD".toLowerCase();  str1.toUpperCase() - "hello world".toUpperCase();  StringBuffer   String Buffer class objects are mutable, so they can be modified. StringBuffer sb = new StringBufer();  String Buffer class defines three constructors: 1. StringBuffer() //empty object 2. StringBuffer(int capacity) //creates empty obj with capacity for storing string 3. StringBuffer(String str) //createStringBufferobjectbyusingastring  StringBuffer Operations: 1. sb.append(str) - adds specified characters at end of StringBuffer object. StringBuffer append(int index, char ch) // indx- pt. where str insrt. 2. sb.insert(indx, str) - To insert characters at specified index location. StringBuffer insert(int index, String str) >> Both methods are overloaded so they can accept any type of data. 3. sb.delete(startIndex, endIndex) - Delete specified substring in StringBuffer. StringBuffer delete(int start, int end) 4. sb.replace() - Replace part of StringBuffer(substring) with another substring. StringBuffer replace(int start, int end, String str) 5. sb.substring(startIndx, endIndx) - Return new string i.e., StringBuffer’s substr String substring(int start) // prints endIndx-1 >> It extracts characters starting from the specified index till the end of the StringBuffer. 6. sb.reverse() - Character sequence is reversed. 7. sb.length() – To find length of StringBuffer. 8. sb.capacity() – To find capacity of StringBuffer. >> Capacity - Amount of storage available for characters that have just been inserted.
  • 41. By- Shalabh Chaudhary [GLAU] 9. sb.charAt(indx) – Find character at particular index position. 10. sb.deletecharAt(indx) – delete character at particular index. Eg.: StringBuffer sb= new StringBuffer("Wipro Technologies"); String result = sb.substring(6); // only startIndex prst System.out.println(result); // Prints Technologies #1. Write a Program that will check whether a given String is Palindrome or not >> import java.util.Scanner; public class PalindromeString { public static void main(String[] args) { Scanner scan=new Scanner(System.in); String s=scan.nextLine(); StringBuffer sb=new StringBuffer(s); sb.reverse(); if(s.equalsIgnoreCase(sb.toString())) System.out.println("Palindrome"); else System.out.println("Not Palindrome"); } } #2. Given two strings, append them together (known as "concatenation") and return the result. However, if the concatenation creates a double- char, then omit one of the chars. If the inputs are “Mark” and “Kate” then the ouput should be “markate”. (The output should be in lowercase) >> import java.util.Scanner; public class AppendString {
  • 42. By- Shalabh Chaudhary [GLAU] public static void main(String[] args) { Scanner scan=new Scanner(System.in); String s1=scan.nextLine(); String s2=scan.nextLine(); if(s1.substring(s1.length()-1).equalsIgnoreCase( s2.substring(0,1))) System.out.println(s1.concat(s2.substring(1,s2.length()))); else System.out.println(s1.concat(s2).toLowerCase()); } } #3. Given string, return new string made of n copies of first 2 chars of the original string where n is the length of the string. The string may be any length. If there are fewer than 2 chars, use whatever is there. If input is "Wipro" then output should be "WiWiWiWiWi". >> public class Copy2Chars{ static String charCopy(String s,int n) { String res=""; if(n<2) return s; else { s=s.substring(0,2); while(n!=0) { res=res.concat(s); n--; } return res; } } public static void main(String args[]) { String s="Wipro"; int n=s.length();
  • 43. By- Shalabh Chaudhary [GLAU] System.out.print(charCopy(s,n)); } } #4. Given a string, if the first or last chars are 'x', return the string without those 'x' chars, and otherwise return the string unchanged. If the input is "xHix", then output is "Hi". >> public class Trimxx{ static String trim(String s,int n) { if (n==1){ if (s.charAt(0) == 'x') return ""; else return s; } if(s.charAt(0)=='x' && s.charAt(n-1)=='x') s=s.substring(1,n-1); return s; } public static void main(String args[]) { String s="xHix"; int n=s.length(); System.out.print(trim(s,n)); } }
  • 44. By- Shalabh Chaudhary [GLAU] #5. Given two strings, word and a separator, return a big string made of count occurrences of the word, separated by the separator string. if the inputs are "Wipro","X" and 3 then the output is "WiproXWiproXWipro". >> public class StringtillCount{ static String strCount(String s,int sep) { String res=""; while(sep>0) { res+=s.concat("X"); sep--; } res=res.substring(0,res.length()-1); return res; } public static void main(String args[]) { String s="Wipro"; int sep=3; System.out.print(strCount(s,sep)); } } #6. Return a version of the given string, where for every star (*) in the string the star and the chars immediately to its left and right are gone. So "ab*cd" yields "ad" and "ab**cd" also yields "ad". >> public class RemoveStar{ static String rmvStr(String s) { StringBuffer sb=new StringBuffer(s); int i=s.indexOf('*'); int l=s.lastIndexOf('*'); return new String(sb.delete(i-1,l+2)); }
  • 45. By- Shalabh Chaudhary [GLAU] public static void main(String args[]) { String s="ab**cd"; System.out.print(rmvStr(s)); } } #7. Given two strings, a and b, create a bigger string made of the first char of a, the first char of b, the second char of a, the second char of b, and so on. Any leftover chars go at the end of the result. If the inputs are "Hello" and "World", then the output is "HWeolrllod". >> public class AlternatePrint{ static String alter(String a,String b) { String res=""; int alen=a.length(); int blen=b.length(); int len=Math.min(alen,blen); int i=0; while(i<len) { res+=a.substring(i,i+1)+b.substring(i,i+1); i++; } if(alen!=blen) res+=b.substring(len); if(blen!=alen) res+=a.substring(len); return res; } public static void main(String args[]) { String a="Hello"; String b="World";
  • 46. By- Shalabh Chaudhary [GLAU] System.out.print(alter(a,b)); } } #8. Given a string and a non-empty word string, return a string made of each char just before and just after every appearance of the word in the string. Ignore cases where there is no char before or after the word, and a char may be included twice if it is between two words. If inputs are "abcXY123XYijk" and "XY", output should be "c13i". If inputs are "XY123XY" and "XY", output should be "13". If inputs are "XY1XY" and "XY", output should be "11". >> public class WordEnds { static String wordAppear(String s, String w) { int slen=s.length(); int wlen=w.length(); String res=""; for (int i=0;i<slen-wlen+1;i++) { String tmp=s.substring(i,i+wlen); if (i>0 && tmp.equals(w)) res+=s.substring(i-1,i); if (i<slen-wlen && tmp.equals(w)) res+=s.substring(i+wlen,i+wlen+1); } return res; } public static void main(String args[]) { String s="abcXY123XYijk"; String w="XY"; System.out.print(wordAppear(s,w)); } }
  • 47. By- Shalabh Chaudhary [GLAU] INTERVIEW QUESTIONS  Q: Explain carefully what null means in Java, and why this special value is necessary. Q: When do we declare a method or class as final explain with example? Q: When do we declare the members of the class as static explain with example? Q: Explain about inner classes with an example? Q: Explain how super keyword is used in overriding the methods? Q: Explain the use of super() method in invoking a constructor? Q: When does a base class variable get hidden, Give reasons? Q: Explain with an example how we can access a hidden base class variable?