0% found this document useful (0 votes)
3 views

Unit-2 ppt - Copy

This document provides an overview of key concepts in Java programming, including classes, objects, constructors, method overloading, access control, static and non-static methods, and inheritance. It explains the structure and functionality of classes, the importance of encapsulation, and various types of inheritance, along with examples for clarity. Additionally, it discusses the String class and inner classes, highlighting their roles in Java programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Unit-2 ppt - Copy

This document provides an overview of key concepts in Java programming, including classes, objects, constructors, method overloading, access control, static and non-static methods, and inheritance. It explains the structure and functionality of classes, the importance of encapsulation, and various types of inheritance, along with examples for clarity. Additionally, it discusses the String class and inner classes, highlighting their roles in Java programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 53

Programming in Java

Unit-2
Classes
• A class in Java is a blueprint for creating objects, defining their
attributes (fields/variables) and behaviors (methods).
• It enables code reusability by allowing multiple objects to be
created from the same class.
• Classes support encapsulation, helping to structure and organize
code efficiently.
• Memory is not allocated for a class until an object is instantiated.

• The syntax for defining a class in Java is as follows:

• class ClassName {
• // Fields (variables)
• // Methods (functions)
• }
Example
• Example:
• class Car {
• String color; // Attribute (field)

• // Method (behavior)
• void drive() {
• System.out.println("Car is driving");
• }
• }
Objects
• An object is an instance of a class, representing a real-world
entity.

• Objects are created from a class blueprint and have state


(attributes/fields) and behavior (methods).

• Each object has a unique identity, even if multiple objects are


created from the same class.

• Memory is allocated for an object when it is instantiated.

• Objects are created using the new keyword.

• Example:
• Car myCar = new Car(); // Creating an object of the Car class
Example
• class Car {
• String color;
• void drive() {
• System.out.println("Car is driving");
• }
• }

• class Main {
• public static void main(String[] args) {
• Car myCar = new Car(); // Creating an object
• myCar.color = "Red";
• myCar.drive();
• }
• }
Output:
• Car is driving
Constructor
• 1.A constructor is a special method used to initialize objects.
• 2. It has the same name as the class and no return type (not
even void).
• 3. Automatically called when an object is created using the
new keyword.
• 4. Used to set initial values for object attributes.
• 5. Can be parameterized (accepts values) or default (no
parameters).
• 6. If no constructor is defined, Java provides a default
constructor automatically.
• There are two types of constructors in Java:

• 1.Default Constructor (No parameters)

• 2.Parameterized Constructor (Takes arguments)


Constructors
• Syntax:
• class ClassName {
• // Constructor
• ClassName() {
• // Initialization code
• }
• }
Default Constructor
• 1. A default constructor is a constructor that takes no
parameters.
• 2. It initializes objects with default values when no specific
values are provided.
• 3. If a class does not have a constructor, Java automatically
provides a default constructor.
• 4. It has the same name as the class and no return type.
• 5. Mainly used for creating objects with default states.
• 6. Can be explicitly defined by the user if custom initialization
is needed.
Example
• class Car {
• // Default Constructor
• Car() {
• System.out.println("A new car is created!");
• }

• void drive() {
• System.out.println("Car is driving");
• }
• }

• class Main {
• public static void main(String[] args) {
• Car myCar = new Car(); // Constructor is automatically called
• myCar.drive();
• }
• }
Output
• A new car is created!
• Car is driving
Method Overloading
• Method Overloading allows multiple methods in a class to
have the same name but with different parameters (varying in
number or type).
• It improves code readability, reusability, and flexibility by
allowing methods to handle different inputs.
• The return type can be different, but changing only the return
type does not overload a method—the parameters must be
different.
• Overloaded methods must have a unique parameter list,
ensuring Java can distinguish them.
• It is commonly used for handling different types of input data
in a consistent way.
Syntax for Method Overloading:
• class ClassName {
• // First method
• void methodName(int a) {
• // Code
• }

• // Overloaded method with different parameters


• void methodName(int a, int b) {
• // Code
• }

• // Overloaded method with different data type


• double methodName(double a) {
• return a * 2;
• }
• }
Example
• class MathOperations {
• // Method with one parameter
• int add(int a) {
• return a + 10;
• }

• // Overloaded method with two parameters


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

• // Overloaded method with three parameters


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

Example
• public class OverloadingExample {
• public static void main(String[] args) {
• MathOperations math = new MathOperations();

• // Calling overloaded methods


• System.out.println("Addition with one parameter: " + math.add(5));
• System.out.println("Addition with two parameters: " + math.add(10,
20));
• System.out.println("Addition with three parameters: " + math.add(1.5,
2.5, 3.0));
• }
• }
Output
• Addition with one parameter: 15
• Addition with two parameters: 30
• Addition with three parameters: 7.0
Access Control
• Access control defines the visibility and accessibility of
classes, methods, and variables in Java.
• It ensures data encapsulation and enhances security by
restricting access to class members.
• Java provides four access modifiers:

• Public → Accessible from anywhere in the program.


• Private → Accessible only within the same class (not visible
outside).
• Protected → Accessible within the same package and in
subclasses (even in different packages).
• Default (No Modifier) → Accessible only within the same
package (also called package-private).
• Helps in controlling access to data and methods, improving
modularity and security.
Example
• class Example {
• public int publicVar = 10; // Public - Accessible anywhere
• private int privateVar = 20; // Private - Accessible only within this class
• protected int protectedVar = 30; // Protected - Accessible within package
& subclasses
• int defaultVar = 40; // Default - Accessible only within the same
package

• void display() {
• System.out.println("Public: " + publicVar);
• System.out.println("Private: " + privateVar);
• System.out.println("Protected: " + protectedVar);
• System.out.println("Default: " + defaultVar);
• }
• }
Example
• public class AccessModifiers {
• public static void main(String[] args) {
• Example obj = new Example();
• obj.display();

• // Accessing public variable directly
• System.out.println("Accessing Public Variable: " + obj.publicVar);
• }
• }
Output
• Public: 10
• Private: 20
• Protected: 30
• Default: 40
• Accessing Public Variable: 10
Static Method
• A static method belongs to the class rather than an
instance (object).

• It can be called without creating an object.

• Cannot access non static variables or methods


directly.

• It can be called by class name without creating object.


Non-Static Methods in Java
 Belong to Objects

 Non-static methods work only when an object is created.

 Can Use Both Static & Non-Static Data

 They can access static and non-static variables of the class.

 Need an Object to Call

 They cannot be called directly inside main().


Example
• class A {
• int a = 10;
• static int b = 20;

• public static void main(String[] args) {


• A r = new A();
• A.show();
• r.disp();
• }

• static void show() {


• System.out.println("show() " + b); // 'a' removed because static
methods can't access non-static members directly.
• }

• void disp() {
• System.out.println("disp() a = " + a + ", b = " + b);
• }
• }
Output
• show() 20
• disp() a = 10, b = 20
String Class
• The java.lang.String class is final, which means no other class can extend
it.

• In Java, String objects are immutable, meaning that once a String is created
and initialized, its value cannot be changed within the same reference.

• String Object Creation:

• String str1 = "My name is Bond"; // Creating a String object

• If two or more String objects have the same sequence of characters, they
share the same reference in the string pool.

• String str1 = "My name is Bond";


• String str2 = "My name is Bond";
• String str3 = "My name " + "is Bond";

• In this case, str1, str2, and str3 refer to the same String object in the string
pool.
Memory Allocation in String Class

str1

str
My Name is Bond

str3
Creating String with new Keyword
• String str5 = new String("My name is Bond");
Example
• class StringExample1 {
• public static void main(String[] args) {
• String s1 = "computer";
• String s2 = "computer";
• String s3 = new String("computer");

• System.out.println("Result 1: " + (s1 == s2)); // true (same reference


in string pool)
• System.out.println("Result 2: " + s1.equals(s2)); // true (content is
same)
• System.out.println("Result 3: " + (s1 == s3)); // false (different
objects)
• System.out.println("Result 4: " + s1.equals(s3)); // true (content is
same)
• }
• }
Output
• Result 1: true
• Result 2: true
• Result 3: false
• Result 4: true
Inheritance

• Inheritance enables a class to reuse properties and methods of another

class, reducing code duplication.

• Uses the extends keyword to inherit from a parent class.

• Supports Single, Multilevel, and Hierarchical Inheritance, but not Multiple

Inheritance (achieved via interfaces).

• The super keyword allows access to parent class methods and constructors.

• Enhances polymorphism, improving flexibility and maintainability in

object-oriented programming.
Example
• class Parent {
• void display() {
• System.out.println("Parent class method");
• }
• }

• class Child extends Parent {


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

• class Main {
• public static void main(String[] args) {
• Child obj = new Child();
• obj.display(); // Inherited from Parent
• obj.show(); // Child class method
• }
• }
Output
• Parent class method
• Child class method
Types of Inheritance in Java
• Single Inheritance
• One class inherits from another.

• Example: A Child class inherits from a Parent class.

• 📌 Diagram:
• Parent
• │
• ▼
• Child
Example
• class Parent {
• void display() {
• System.out.println("Parent class method");
• }
• }

• class Child extends Parent {


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

• class Main {
• public static void main(String[] args) {
• Child obj = new Child();
• obj.display();
• obj.show();
• }
• }
Output
• Parent class method
• Child class method
Multilevel Inheritance
• In multilevel inheritance, a class inherits from another class, which is
further inherited by a third class.

• 📌 Diagram:

• Grandparent
• │
• ▼
• Parent
• │
• ▼
• Child
Example
• class Grandparent {
• void methodA() {
• System.out.println("Grandparent method");
• }
• }
• class Parent extends Grandparent {
• void methodB() {
• System.out.println("Parent method");
• }
• }
• class Child extends Parent {
• void methodC() {
• System.out.println("Child method");
• }
• }
• class Main {
• public static void main(String[] args) {
• Child obj = new Child();
• obj.methodA();
• obj.methodB();
• obj.methodC();
• }
• }
Output
• Grandparent method
• Parent method
• Child method
Hierarchical Inheritance
• In hierarchical inheritance, a single parent class is inherited by multiple child
classes. This allows different subclasses to share common properties and behaviors
from a common superclass.

• 📌 Diagram:

Parent
/ \
• Child1 Child2
Example
• class Parent {
• void show() {
• System.out.println("Parent method");
• }
• }
• class Child1 extends Parent {
• void display1() {
• System.out.println("Child1 method");
• }
• }
• class Child2 extends Parent {
• void display2() {
• System.out.println("Child2 method");
• }
• }
• class Main {
• public static void main(String[] args) {
• Child1 obj1 = new Child1();
• obj1.show();
• obj1.display1();
• Child2 obj2 = new Child2();
• obj2.show();
• obj2.display2();
• }
• }
Output
• Parent method
• Child1 method
• Parent method
• Child2 method
Multiple Inheritance (Using Interfaces)
• Java does not support multiple inheritance with classes but allows it
using interfaces.

• 📌 Diagram:

• Interface1 Interface2
• │ │
• ▼ ▼
• Class (Implements Both)
Overriding Methods
• Definition: Method Overriding allows a subclass to provide its own implementation of a
method that is already defined in its superclass.

• Key Points:

• Same Method Signature: The method in the subclass must have the same name, same return
type, and same parameter list as the method in the parent class.

• Occurs at Runtime: Method overriding is a form of runtime polymorphism.

• @Override Annotation: Optional but recommended for clarity and to prevent errors.

• Cannot Override final, static, and private methods: These methods cannot be overridden.

• Access Modifier: The access level of the overridden method must be at least as accessible as
the method in the superclass (e.g., public or protected).

• Exception Handling: The subclass method can throw the same or a subclass of the exceptions
declared in the parent method.
Benefits
 Promotes polymorphism (same method behaves differently for different
objects).

 Allows child classes to modify or extend the behavior of parent class


methods.
Example
• class Parent {
• void display() {
• System.out.println("Parent class method");
• }
• }

• class Child extends Parent {


• @Override
• void display() {
• System.out.println("Child class method");
• }
• }

• public class Main {


• public static void main(String[] args) {
• Parent obj = new Child();
• obj.display(); // Calls Child class method
• }
• }
Output
• Child class method
Inner Class
• An Inner Class is a class defined inside another class. It helps
in grouping related classes together and improves
encapsulation
• A class defined inside another class.

• Improves encapsulation and logical grouping of related


classes.

• Can access private members of the outer class.

• Helps in reducing code complexity.


Types of Inner Class
• Member Inner Class – A non-static class inside another class.
• Static Nested Class – A static class inside another class (does not require an
instance of the outer class).
• Local Inner Class – Defined inside a method, accessible only within that
method.
• Anonymous Inner Class – A class without a name, usually used for short-
lived objects (often with interfaces or abstract classes).

• Why Use Inner Classes?


• ✅ Helps in logical grouping of related classes.
• ✅ Improves encapsulation (hides implementation details).
• ✅ Can access private members of the outer class.
• ✅ Reduces code complexity by keeping classes within classes when
needed.
Example
• class Outer {
• class Inner { // Member Inner Class
• void show() {
• System.out.println("Hello from Inner Class!");
• }
• }

• public static void main(String[] args) {


• Outer outer = new Outer(); // Creating Outer class object
• Outer.Inner inner = outer.new Inner(); // Creating Inner class object
• inner.show(); // Calling Inner class method
• }
• }
Output
• Hello from Inner Class!
Super Abstract Class
• Cannot be instantiated – An abstract class cannot create objects directly.
• Can have abstract & non-abstract methods – Abstract methods must be
implemented in subclasses, while non-abstract methods can have
definitions.
• Declared using abstract keyword – Example: abstract class Animal {}.
• Supports inheritance – Subclasses inherit properties & behaviors from
the abstract class.
• Must be extended – A subclass must override all abstract methods unless
it is also abstract.
• Can have constructors – Abstract classes can have constructors, which
are called when a subclass object is created.
• Used for code reusability – Common functionalities can be defined once
and shared among multiple subclasses
Example
• abstract class Animal {
• abstract void makeSound(); // Abstract method (no body)
• }

• class Dog extends Animal {


• void makeSound() {
• System.out.println("Dog barks");
• }
• }

• public class Main {


• public static void main(String[] args) {
• Animal myDog = new Dog(); // Creating object of subclass
• myDog.makeSound();
• }
• }
Output
• Dog barks

You might also like