0% found this document useful (0 votes)
11 views84 pages

Unit 2

The document outlines the course structure for Java Programming at Pimpri Chinchwad University, detailing course objectives and learning outcomes. It covers fundamental concepts such as classes, objects, constructors, methods, access modifiers, recursion, and the String class, providing examples for each topic. The document serves as a comprehensive guide for students to understand and apply Java programming principles.

Uploaded by

bhayu773
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views84 pages

Unit 2

The document outlines the course structure for Java Programming at Pimpri Chinchwad University, detailing course objectives and learning outcomes. It covers fundamental concepts such as classes, objects, constructors, methods, access modifiers, recursion, and the String class, providing examples for each topic. The document serves as a comprehensive guide for students to understand and apply Java programming principles.

Uploaded by

bhayu773
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 84

1

PCET’S Pimpri Chinchwad University

Department of Computer Science and Engineering


Course Name : Java Programming
Course Code/Course Type : UBTCE212/PCC
SY. B.Tech

Prepared By: Mr. Ankush Dahat

PIMPRI CHINCHWAD UNIVERSITY


2

Course Objectives (CO):


• The objectives of Java Programming are:
To learn the fundamentals of the Java programming language.
To learn object-oriented principles like abstraction, encapsulation,
inheritance, and polymorphism and apply them in solving problems using
java.
To apply the concepts of exception handling, multithreading and collection
classes using java.

To develop software applications using JDBC connectivity.


To design the Graphical User Interface using applets and swing controls.
PIMPRI CHINCHWAD UNIVERSITY
3

Course Learning Outcomes (CLO):


• Students would be able to:
To grasp the fundamentals programming concepts of Java programming
language.

To apply object-oriented principles like abstraction, encapsulation,


inheritance, polymorphism in solving problems using java.
To perform exception handling, multithreading code using java.
To develop software applications using JDBC connectivity.
To design the Graphical User Interface using event handling.

PIMPRI CHINCHWAD UNIVERSITY


UNIT- II
Classes, Objects, Inheritance &
Polymorphism in Java
5

Classes and Objects in Java


• Class:
A class is a blueprint or prototype from which objects are created. It
can contain fields (variables) and methods to define the properties
and behavior of an object.
class ClassName {
// fields
int field1;
String field2;
// methods
void method1() {
// logic
}
} PIMPRI CHINCHWAD UNIVERSITY
6

Classes and Objects in Java


• Object:
An object is an instance of a class. It is created using the new
keyword.

ClassName obj = new ClassName();

PIMPRI CHINCHWAD UNIVERSITY


7

Classes and Objects in Java - Example


class Student {
int id;
String name;
void display() {
System.out.println("ID: " + id + ", Name: " + name);
}
}

public class Main {


public static void main(String[] args) {
Student s = new Student();
s.id = 101;
s.name = "John";
s.display();
}
}
PIMPRI CHINCHWAD UNIVERSITY
8

Constructors
• A constructor is a special method used to initialize objects. It has the same
name as the class and no return type.

PIMPRI CHINCHWAD UNIVERSITY


9

Default Constructor:
• Automatically provided by Java if no
• constructor is explicitly defined.

class Student
{ int id; public class Main {
String public static void main(String[] args) {
name; Student s = new Student();
Student() { s.display();
id = 0; }
name = "Unknown"; }
}
void display() {
System.out.println("ID: " + id + ", Name: " + name);
}
} PIMPRI CHINCHWAD UNIVERSITY
9

Default Constructor:
class DefaultConstructorExample {
int x;

DefaultConstructorExample() {
x = 10; // Assign default value
System.out.println("Default constructor called. Value of x: " + x);
}

public static void main(String[] args) {


DefaultConstructorExample obj = new DefaultConstructorExample();
}
}
PIMPRI CHINCHWAD UNIVERSITY
11

Parameterized Constructor:
• Used to initialize fields with specific
`
values.
• class Student {
public class Main {
int id; public static void main(String[] args)
String name; { Student s = new Student(101, "John"); s.display();
Student(int id, String name) }
}
{ this.id = id;
this.name = name;
}
void display() {
System.out.println("ID: " + id + ", Name: " +
name);
} PIMPRI CHINCHWAD UNIVERSITY
12

Parameterized Constructor:

class ParameterizedConstructorExample {
int x;

ParameterizedConstructorExample(int value) {
x = value;
System.out.println("Parameterized constructor called. Value of x: " + x);
}

public static void main(String[] args) {


ParameterizedConstructorExample obj = new ParameterizedConstructorExample(20);
}
}

PIMPRI CHINCHWAD UNIVERSITY


12

Copy Constructor:
class CopyStudent {
int x;

CopyStudent(int value) {
x = value;
}

CopyStudent(CopyStudent obj) {
x = obj.x;
System.out.println("Copy constructor called. Value of x: " + x);
}

public static void main(String[] args) {


CopyStudent obj1 = new CopyStudent (30);
CopyStudent obj2 = new CopyStudent (obj1);
}
}
PIMPRI CHINCHWAD UNIVERSITY
13

Constructor Overloading:
• Allows multiple constructors with different parameter lists.
void display() {
class Student {
System.out.println("ID: " + id + ", Name: " + name);
int id;
}
String name;
}
Student() {
public class Main {
id = 0;
public static void main(String[] args) {
name = "Unknown";
Student s1 = new Student();
}
s1.display();
Student(int id, String name) {
Student s2 = new Student(102, "Alice");
this.id = id;
s2.display();
this.name = name;
}
}
}
PIMPRI CHINCHWAD UNIVERSITY
14

Constructor Overloading:
class ConstructorOverloadingExample {
int x;

ConstructorOverloadingExample() {
x = 10;
}
ConstructorOverloadingExample(int value) {
x = value;
}
public static void main(String[] args) {
ConstructorOverloadingExample obj1 = new ConstructorOverloadingExample();
ConstructorOverloadingExample obj2 = new ConstructorOverloadingExample(40);

System.out.println("Value of x in obj1: " + obj1.x);


System.out.println("Value of x in obj2: " + obj2.x);
}
} PIMPRI CHINCHWAD UNIVERSITY
14

Static Block vs Constructor

class StaticBlockVsConstructor {
static {
System.out.println("Static block called.");
}

StaticBlockVsConstructor() {
System.out.println("Constructor called.");
}

public static void main(String[] args) {


System.out.println("Main method started.");
StaticBlockVsConstructor obj = new StaticBlockVsConstructor();
}
} PIMPRI CHINCHWAD UNIVERSITY
15

Methods
• Methods define the behavior of a class. They can accept parameters and return
values.

PIMPRI CHINCHWAD UNIVERSITY


16

Example 1: Method with Parameters


class Calculator {
int add(int a, int b) {
return a + b;
}
}

public class Main {


public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println("Sum: " + calc.add(5, 10));
}
}
PIMPRI CHINCHWAD UNIVERSITY
17

Example 2: Method without Parameters


class Greetings {
void sayHello() {
System.out.println("Hello, World!");
}
}

public class Main {


public static void main(String[] args) {
Greetings greet = new Greetings();
greet.sayHello();
}
}

PIMPRI CHINCHWAD UNIVERSITY


18

Static Fields and Methods


• Static fields and methods belong to the class rather than any object. They are
accessed using the class name.

PIMPRI CHINCHWAD UNIVERSITY


class ObjectCounter {
static int count = 0; // Static field

ObjectCounter() {
count++;
}

static void displayCount() { // Static method


System.out.println("Total objects created: " + count);
}

public static void main(String[] args) {


ObjectCounter obj1 = new ObjectCounter();
ObjectCounter obj2 = new ObjectCounter();
ObjectCounter obj3 = new ObjectCounter();

ObjectCounter.displayCount();
}
19

Static Fields and Methods


class Counter {
static int count = 0;

Counter() {
count++;
}

static void displayCount() {


System.out.println("Count: " + count);
}
}

public class Main {


public static void main(String[] args) {
new Counter();
new Counter();
Counter.displayCount(); // Count : 2
}
} PIMPRI CHINCHWAD UNIVERSITY
19

Static Fields and Methods


class MathUtils {
static int add(int a, int b) { // Static method
return a + b;
}

static int multiply(int a, int b) { // Static method


return a * b;
}
}

public class Main {


public static void main(String[] args) {
// Calling static methods without creating an object
System.out.println("Sum: " + MathUtils.add(5, 10));
System.out.println("Product: " + MathUtils.multiply(4, 7));
}
}

PIMPRI CHINCHWAD UNIVERSITY


19

Static Fields and Methods


class StaticExample {
static String companyName; // Static field

// Static block to initialize static fields


static {
companyName = "TechCorp";
System.out.println("Static block executed.");
}

static void displayCompanyName() {


System.out.println("Company Name: " + companyName);
}

public static void main(String[] args) {


// Accessing static method and field without an object
StaticExample.displayCompanyName();
}
}
PIMPRI CHINCHWAD UNIVERSITY
Access modifiers
Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
Default: The access level of a default modifier is only within the package. It cannot
be accessed from outside the package. If you do not specify any access level, it will
be the default.
Protected: The access level of a protected modifier is within the package and
outside the package through child class. If you do not make the child class, it cannot
be accessed from outside the package.
Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
Private
class A{
private int data=40;
private void msg()
{
System.out.println("Hello java");}
}

public class Simple{


public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);
obj.msg();
}
}
Private Constructor
class A{
private A() //private constructor
{
}
void msg()
{
System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
}
}
Default
We don’t use any default keyword
Default
//save by A.java
package pack;
class A{
void msg()
{
System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//
obj.msg();//
}
}
Protected
//save by A.java
package pack;
public class A
{
protected void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
To public class filename should be same as that of class
On single file two public file names wont be there
Public

//save by A.java
package pack;
public class A{
public void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Can a class in Java be declared as private or protected?

What will happen if you declare the main() method as private?


22

this Reference
• The “this” keyword in Java refers to the current object of a class. It is primarily
used to resolve conflicts between instance variables and parameters when their
names are the same.

PIMPRI CHINCHWAD UNIVERSITY


23

this Reference - Example


class Student {
int id;
String name;
Student(int id, String name) {
this.id = id; // Refers to the instance variable
this.name = name;
}
void display() {
System.out.println("ID: " + id + ", Name: " + name);
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student(101, "John");
s.display();
}
}

PIMPRI CHINCHWAD UNIVERSITY


24

Recursion
• Recursion is a technique in which a method calls itself to solve a smaller instance
of the same problem.

PIMPRI CHINCHWAD UNIVERSITY


25

Recursion - Example
class Factorial {
int calculateFactorial(int n) {
if (n == 1) return 1; // Base case
return n * calculateFactorial(n - 1);
}
}

public class Main {


public static void main(String[] args) {
Factorial fact = new Factorial();
System.out.println("Factorial of 5: " + fact.calculateFactorial(5));
}
}

PIMPRI CHINCHWAD UNIVERSITY


26

Exploring String Class


• The String class in Java is used to create and manipulate sequences of characters.
Strings in Java are immutable, meaning their values cannot be changed once
created.

• Common String Methods:


1. concat(): Concatenates two strings.
2. length(): Returns the length of the string.
3. charAt(): Returns the character at a specified index.
4. substring(): Extracts a substring.
PIMPRI CHINCHWAD UNIVERSITY
27

Exploring String Class


public class Main {
public static void main(String[] args) {
String str = "Java Programming";
System.out.println("Length: " + str.length());
System.out.println("Character at index 5: " + str.charAt(5));
System.out.println("Substring: " + str.substring(0, 4));
System.out.println("Concatenation: " + str.concat(" is fun!"));
}
}

PIMPRI CHINCHWAD UNIVERSITY


28

Exploring String Class


Method Description

char charAt(int index) Returns the character at the specified index.

int compareTo(String another) Compares two strings lexicographically.

boolean equals(Object obj) Checks if two strings are equal.

boolean equalsIgnoreCase(String another) Checks if two strings are equal, ignoring case considerations.

String concat(String str) Concatenates the specified string to the end of the current string.

boolean contains(CharSequence s) Checks if the string contains the specified sequence of characters.

boolean startsWith(String prefix) Checks if the string starts with the specified prefix.

boolean endsWith(String suffix) Checks if the string ends with the specified suffix.

int indexOf(String str) Returns the index of the first occurrence of the specified substring.

int lastIndexOf(String str) Returns the index of the last occurrence of the specified substring.

String substring(int beginIndex) Returns a new string starting from the specified index.

String substring(int beginIndex, int endIndex) Returns a substring from the start index to the end index (exclusive).

String toLowerCase() Converts all characters in the string to lowercase.


29

Exploring String Class


Method Description

String toUpperCase() Converts all characters in the string to uppercase.

String trim() Removes leading and trailing whitespace.

int length() Returns the length of the string.

String replace(char oldChar, char newChar) Replaces all occurrences of a character with another character.

String replace(CharSequence target, CharSequence


Replaces all occurrences of a substring with another substring.
replacement)

boolean isEmpty() Checks if the string is empty (length is 0).

String[] split(String regex) Splits the string around matches of the given regular expression.

String join(CharSequence delimiter, CharSequence...


Joins the elements with the specified delimiter.
elements)

char[] toCharArray() Converts the string into a character array.

static String valueOf(Object obj) Returns the string representation of the specified object.

boolean matches(String regex) Checks if the string matches the given regular expression.

int hashCode() Returns the hash code of the string.


30

Garbage Collection
• Garbage Collection (GC) in Java is an automated process that manages
memory by reclaiming memory occupied by objects that are no longer in
use.
• It helps prevent memory leaks and ensures efficient memory utilization.

PIMPRI CHINCHWAD UNIVERSITY


30

Garbage Collection: Key Features


• Automatic Memory Management: The JVM handles memory cleanup,
freeing developers from manual memory deallocation.
• Focus on Unreachable Objects: Objects that cannot be accessed by any live
thread or reference are considered for garbage collection.
• Non-Deterministic: Garbage collection occurs at the discretion of the JVM,
not at a specific time.
• Managed by the Garbage Collector: A part of the JVM, the Garbage
Collector identifies and removes unused objects from memory.

PIMPRI CHINCHWAD UNIVERSITY


31

Garbage Collection
class Demo {
protected void finalize() throws Throwable {
System.out.println("Object is garbage collected");
}
}

public class Main {


public static void main(String[] args) {
Demo obj = new Demo();
obj = null; // Dereference the object
System.gc(); // Suggest garbage collection
}
}

The finalize() method is called by the garbage collector before the object is destroyed. The System.gc()
method is a request to initiate garbage collection, though its execution depends on the JVM.

PIMPRI CHINCHWAD UNIVERSITY


32

Inheritance
• Inheritance allows a class to acquire properties and behaviors from another class,
promoting code reuse and organization.

• Types of Inheritance:
1. Single Inheritance: A class inherits from one parent class.
2. Multilevel Inheritance: A class inherits from a parent class, which is
itself a child of another class.
3. Hierarchical Inheritance: Multiple classes inherit from a single parent
class.

PIMPRI CHINCHWAD UNIVERSITY


Inheritance
Inheritance
Terms used in Inheritance
Class
Sub Class/Child Class
Super Class/Parent Class
Reusability
Single Inheritance
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
class Animal{
void eat(){
System.out.println("eating...");
}
}
class Dog extends Animal{
void bark(){
System.out.println("barking...");
}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}
}
Multilevel Inheritance Example
class Animal{
void eat(){
System.out.println("eating...");}
}
class Dog extends Animal{
void bark()
{System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep()
{System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Hierarchical Inheritance Example
class Animal{
void eat()
{System.out.println("eating...");}
}
class Dog extends Animal{
void bark()
{System.out.println("barking...");}
}
class Cat extends Animal{
void meow()
{System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
c.bark();//
}}
33

Inheritance
class Parent {
void displayParent() {
System.out.println("This is the parent class.");
}
}

class Child extends Parent {


void displayChild() {
System.out.println("This is the child class.");
}
}

public class Main {


public static void main(String[] args) {
Child c = new Child();
c.displayParent();
c.displayChild();
}
} PIMPRI CHINCHWAD UNIVERSITY
34

Using super Keyword:


• The super keyword is used to access methods and constructors of the parent class.

PIMPRI CHINCHWAD UNIVERSITY


35

Using super Keyword:


class Parent {
void show() {
System.out.println("Parent class method");
}
}

class Child extends Parent {


void show() {
super.show();
System.out.println("Child class method");
}
}

public class Main {


public static void main(String[] args) {
Child c = new Child();
c.show();
}
} PIMPRI CHINCHWAD UNIVERSITY
35

Using super Keyword:


class Parent {
String message = "Message from Parent";
}

class Child extends Parent {


String message = "Message from Child";

void displayMessages() {
System.out.println(message);
System.out.println(super.message);
}
}

public class Main {


public static void main(String[] args) {
Child child = new Child();
child.displayMessages();
}
} PIMPRI CHINCHWAD UNIVERSITY
35

Using super Keyword:


class Parent {
Parent(String message) {
System.out.println("Parent Constructor: " + message);
}
}

class Child extends Parent {


Child(String message) {
super("Message for Parent");
System.out.println("Child Constructor: " + message);
}
}

public class Main {


public static void main(String[] args) {
Child child = new Child("Message for Child");
}
} PIMPRI CHINCHWAD UNIVERSITY
39

Polymorphism
• Polymorphism in Java is the ability of an object to take many forms. It allows
methods to perform different tasks based on the object that calls them, enhancing
code flexibility and reusability.

PIMPRI CHINCHWAD UNIVERSITY


40

Polymorphism
• Types of Polymorphism
• Polymorphism in Java can be broadly categorized into:
1. Compile-Time Polymorphism (Static Polymorphism)
2. Run-Time Polymorphism (Dynamic Polymorphism)

PIMPRI CHINCHWAD UNIVERSITY


41

Polymorphism
• Compile-Time Polymorphism (Static Polymorphism)
Explanation:Compile-time polymorphism is achieved through method
overloading. The method to be invoked is determined at compile-time
based on the method signature.
• Method Overloading
• Method overloading occurs when multiple methods in the same class
share the same name but differ in:
1. Number of parameters
2. Type of parameters
3. Sequence of parameters

PIMPRI CHINCHWAD UNIVERSITY


42

Polymorphism
class Calculator {
// Method to add two integers
int add(int a, int b) {
return a + b;
}

// Overloaded method to add three integers


int add(int a, int b, int c) {
return a + b + c;
}

// Overloaded method to add two double values


double add(double a, double b) {
return a + b;
}
}

PIMPRI CHINCHWAD UNIVERSITY


43

Polymorphism
public class MethodOverloadingExample {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println("Sum of 2 integers: " + calc.add(10, 20));
System.out.println("Sum of 3 integers: " + calc.add(10, 20, 30));
System.out.println("Sum of 2 doubles: " + calc.add(10.5, 20.5));
}
}

PIMPRI CHINCHWAD UNIVERSITY


44

Polymorphism
• Run-Time Polymorphism (Dynamic Polymorphism)
Explanation:Run-time polymorphism is achieved through method
overriding. The method to be invoked is determined at run time based
on the object's actual type.
• Method Overriding
• Method overriding occurs when a subclass provides a specific
implementation of a method already defined in its superclass.
• The overriding method must have:
1. The same method name
2. The same return type
3. The same parameter list

PIMPRI CHINCHWAD UNIVERSITY


45

Polymorphism
class Animal {
void sound() {
System.out.println("This is a generic animal sound.");
}
public class MethodOverridingExample {
}
public static void main(String[] args) {
Animal animal;
class Dog extends Animal {
@Override
animal = new Dog(); // Dog-specific sound
void sound() {
animal.sound();
System.out.println("The dog barks.");
}
} animal = new Cat(); // Cat-specific sound
animal.sound();
}
class Cat extends Animal {
}
@Override
void sound() {
System.out.println("The cat meows.");
}
} PIMPRI CHINCHWAD UNIVERSITY
47

Key Differences: Compile-Time vs. Run-Time


Polymorphism
Compile-Time Run-Time
Aspect
Polymorphism Polymorphism

Achieved Through Method Overloading Method Overriding

Binding Time Compile Time Run Time

Inheritance Required No Yes

Less flexible, more More flexible, supports


Flexibility
deterministic dynamic behavior

Overriding the sound()


Add(int a, int b) and
Example method in Animal
Add(double a, double b)
subclasses

PIMPRI CHINCHWAD UNIVERSITY


36

Preventing Inheritance:
• Using the final keyword prevents inheritance of classes or overriding of methods.

PIMPRI CHINCHWAD UNIVERSITY


37

Preventing Inheritance:
final class FinalClass {
}

// class SubClass extends FinalClass { //

//}

class Parent {
final void display() {
System.out.println("Final method");
}
}

class Child extends Parent {


void display()
{ //
// }
} PIMPRI CHINCHWAD UNIVERSITY
37

Final Variables
public class FinalVariableExample {
final int CONSTANT = 100; // Final variable

void display() {
// CONSTANT = 200; //
System.out.println("CONSTANT: " + CONSTANT);
}

public static void main(String[] args) {


FinalVariableExample obj = new FinalVariableExample();
obj.display();
}
}

PIMPRI CHINCHWAD UNIVERSITY


37

Final Methods
class Parent {
final void display() {
System.out.println("Final method in Parent class");
}
}
class Child extends Parent {
// void display() { }
}

PIMPRI CHINCHWAD UNIVERSITY


37

Final Classes
final class FinalClass {
void display() {
System.out.println("This is a final class");
}
}
class Child extends FinalClass { } //

PIMPRI CHINCHWAD UNIVERSITY


37

Final with Static


public class FinalParameterExample {
void display(final int num) {
num = 20; //
System.out.println("Number: " + num);
}

public static void main(String[] args) {


FinalParameterExample obj = new FinalParameterExample();
obj.display(10);
}
}

PIMPRI CHINCHWAD UNIVERSITY


37

Abstract Classes and Implementation


abstract class Vehicle { // Abstract class
abstract void start(); // Abstract method (no implementation)

void stop() { // Concrete method (has implementation)


System.out.println("Vehicle is stopping...");
}
}

PIMPRI CHINCHWAD UNIVERSITY


37

Abstract Classes and Implementation


abstract class Animal {
abstract void makeSound(); // Abstract method
}

class Dog extends Animal {

void makeSound() {
System.out.println("Bark!");
}
}

PIMPRI CHINCHWAD UNIVERSITY


37

Abstract Classes and Implementation


abstract class Animal {
abstract void makeSound(); // Abstract method class Main {
public static void main(String[] args) {
void sleep() { // Concrete method Animal myDog = new Dog();
System.out.println("Sleeping..."); myDog.makeSound();
} myDog.sleep();
} }
}
class Dog extends Animal {
void makeSound() { // Implementing abstract method
System.out.println("Bark!");
}
}

PIMPRI CHINCHWAD UNIVERSITY


37

Abstract Classes and Implementation


abstract class Shape
{ Shape()
{
System.out.println("Shape Constructor Called");
}
abstract void draw();
}

PIMPRI CHINCHWAD UNIVERSITY


37

Abstract Classes and Implementation


abstract class Shape
{ Shape()
{
System.out.println("Shape Constructor Called");
}
abstract void draw();
}

PIMPRI CHINCHWAD UNIVERSITY


37

Key Features of Abstract Classes:


1.Cannot be instantiated: You cannot create an object of an abstract class.
2.Can contain both abstract and concrete methods: Allows method definitions along with method
declarations.
3.Can have constructors: An abstract class can have a constructor, which can be called via its
subclasses.
4.Can have instance variables and static methods.
5.Supports inheritance: A subclass must provide implementations for all abstract methods unless it is also
an abstract class.

PIMPRI CHINCHWAD UNIVERSITY


48

Assignment Questions
1. Student Management System: Create a Student class with fields like id, name, and
marks. Add methods to display details and calculate grades based on marks. Write
a program to create multiple student objects and display their details and grades.
2. Bank Account Simulation: Create a BankAccount class with fields accountNumber,
accountHolderName, and balance. Implement methods for deposit, withdrawal,
and displaying account details. Ensure balance does not go negative.
3. Default Constructor for Book Details: Create a Book class with fields title, author,
and price. Use a default constructor to initialize default values and display them.

PIMPRI CHINCHWAD UNIVERSITY


49

Assignment Questions
4. Parameterized Constructor for Employee Details: Create an Employee class with
fields id, name, and salary. Use a parameterized constructor to initialize the fields
and display the employee details.
5. Constructor Overloading for Shapes: Create a Shape class with overloaded
constructors:
a. Default constructor initializes a circle with a default radius.
b. A constructor with parameters initializes a rectangle with length and
breadth.
c. Write a program to calculate the area based on the constructor invoked.

PIMPRI CHINCHWAD UNIVERSITY


50

Assignment Questions
6. Track Object Count: Create a Product class with a static field productCount to track
the number of objects created. Use a static method to display the total count.
7. Temperature Converter: Create a Temperature class with a static method to
convert temperature between Celsius and Fahrenheit. Write a program to
demonstrate its usage.
8. Access Control in Employee Details: Create an Employee class with fields id
(private), name (protected), and department (public). Use appropriate access
modifiers and demonstrate access in another class within the same package and a
subclass.
PIMPRI CHINCHWAD UNIVERSITY
51

Assignment Questions
9. Using this to Resolve Conflicts: Create a Car class with fields brand, model, and price. Use
the this keyword in the constructor to differentiate between instance variables and
parameters with the same name.
10. Fibonacci Series: Write a program to calculate the nth Fibonacci number using recursion.
11. Sum of Digits: Write a recursive program to calculate the sum of digits of a given number.
12. Text Analysis: Write a program to process a paragraph of text and perform the following
operations:
1. Count the number of words.
2. Find and replace a specific word.
3. Extract the first sentence.
4. Convert the text to uppercase and lowercase.
PIMPRI CHINCHWAD UNIVERSITY
52

Assignment Questions
13. Palindrome Check: Write a program to check if a given string is a palindrome.
Ignore case and spaces.
14. Object Cleanup: Create a Resource class with a finalize() method to display a
message when an object is garbage collected. Write a program to demonstrate
garbage collection.
15. Vehicle Inheritance: Create a base class Vehicle with a method move(). Create
subclasses Car and Bike that override the move() method with specific
implementations. Demonstrate runtime polymorphism by calling the move()

method on different object types.


PIMPRI CHINCHWAD UNIVERSITY

You might also like