Unit 2 Classess and Objects - Updated
Unit 2 Classess and Objects - Updated
Definition of a Class
A class is a template that specifies the attributes and behavior of things or objects.
A class is a blueprint or prototype from which objects are created.
A class is the implementation of an abstract data type (ADT).
Class is a combination of Data Members and Member Functions.
Syntax of a Class
classClassName {
Datatype variable1;
Datatype variable2; DataMembers
Datatype variableN;
Key Characteristics
Method Syntax
return_typemethod_name(parameter-list) {
// body of method
}
return_type: Specifies the type of data the method returns. If no value is returned, the
type must be void.
method_name: Specifies the name of the method. It must be a unique identifier within
the current scope.
parameter-list: A sequence of type and identifier pairs separated by commas. If no
parameters exist, the list is empty.
Return Value
Methods with a return type other than void use the return statement to pass values
back to the calling method.
Syntax:
return value;
classResult {
doublemarks1 = 89;
doublemarks2 = 95;
doublemarks3 = 92;
doublepercentage() {
return(marks1 +marks2+marks3)/3;
}
}
var_name = object_name.method_name(parameter-list);
Example:
In the above example, r1 is an object. The method percentage() is called and assigned to
the variable per.
Java provides several access modifiers to define visibility and access levels for classes, variables,
methods, and constructors. The four access levels are:
1. Package/Friendly (Default)
o Visible to all classes within the same package.
o No explicit modifier is needed.
2. Private
o Visible only within the class where it is declared.
3. Public
o Visible within the class and to all other classes, regardless of package.
4. Protected
o Visible within the same package and accessible by subclasses.
Example:
Class A
{
String str = "Hi";
void a() {
System.out.println(str);
}
}
Methods, variables, and constructors declared private are only accessible within the
same class.
This is the most restrictive access level.
Classes and interfaces cannot be declared private.
To expose private variables outside the class, getter and setter methods must be used.
Example:
class A {
private String s1 = "Hello";
String getName() {
returns1;
}
}
In the above example, s1 is private, meaning it cannot be accessed directly from other
classes. The getName() method provides controlled access to it.
The main() method must always be public so that the Java interpreter can call it to start
the program.
Example:
package p1;
class A {
float f1;
protectedint i1;
}
package p1;
class B {
public void getData() {
A a1 = new A(); // Instance of class A
a1.f1 = 19;
a1.i1 = 12; // Accessing protected variable
}
}
2.3 Constructor
Definition
Types of Constructors
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
1. Default Constructor
Example:
class A {
A() { // Default constructor
System.out.println("Default constructor called..");
}
Output:
2. Parameterized Constructor
void display() {
System.out.println("Value of parameterized constructor is :: " + a + " and " + s1);
}
Output:
3. Copy Constructor
A copy constructor is a constructor that takes one parameter of the same class type.
It is used to create a new object as a copy of an existing object.
The copy is independent of the original object, occupying a different memory address.
Example:
class Triangle {
doublebase, height;
// Copy constructor
Triangle(Triangle t1) {
base = t1.base;
height = t1.height;
}
}
4. Overloaded Constructors
Constructor overloading allows defining multiple constructors within a class, each with a
different signature.
Unlike methods, constructors do not have a return type.
Example:
class Triangle {
double base, height;
classconstructor_ex {
public static void main(String[] args) {
Triangle t1 = new Triangle(); //Default constructor call
Triangle t2 = new Triangle(10, 20); // Parameterized constructor call
Triangle t3 = new Triangle(t2); // copy constructor call
2.4 Inheritance
Definition
Inheritance is the process by which a class can acquire the properties and methods of its
parent class.
A child class (derived class) is created from a parent class (base class).
Inheritance enables:
o Reusability: Methods and fields from the parent class can be reused.
o Extensibility: New methods and fields can be added to the child class.
All properties of a superclass, except private members, can be inherited in a subclass
using the extendskeyword.
The inherited fields can be used directly, just like any other fields. You can declare a field
in the subclass with the same name as the one in the superclass.
You can declare new fields in the subclass that are not in the superclass.
The inherited methods can be used directly as they are.
You can write a new instance method in the subclass that has the same signature as the
one in the superclass.(overriding it).
Types of Inheritance
Single Inheritance:
A class is derived from a single parent class.
Example:
class A {
public void displayA() {
System.out.println("Class A method");
}
}
class B extends A {
public void displayB() {
System.out.println("Class B method");
}
}
Multilevel Inheritance:
A class is derived from a class that is itself derived from
another class.
Example:
class A { ... }
class B extends A { ... }
class C extends B { ... }
Multiple Inheritance:
Not supported directly in Java through classes to avoid
ambiguity.
Hierarchical Inheritance:
Multiple classes are derived from a single parent class.
Example:
class A { ... }
class B extends A { ... }
class C extends A { ... }
Hybrid Inheritance:
Combination of single and multiple inheritance. Not
directly supported in Java.
Example
class A {
void displayA() {
System.out.println("Class A method");
}
}
class B extends A { // Single Inheritance
void displayB() {
System.out.println("Class B method");
}
}
class C extends B { // Multilevel Inheritance
void displayC() {
System.out.println("Class C method");
}
}
class D extends A { // Hierarchical Inheritance
void displayD() {
System.out.println("Class D method");
}
}
class Trial {
public static void main(String[] args) {
B b = new B();
C c = new C();
D d = new D();
b.displayB();
c.displayC();
d.displayD();
}}
2.4.1 Encapsulation
Definition
Encapsulation is the mechanism of binding together data and the methods that
manipulate it, hiding implementation details from the outside world.
It combines data hiding and abstraction.
Achieved by:
o Declaring variables as private.
o Providing public getter and setter methods for controlled access.
Example:
class Person {
private String name;
privateint age;
class Main {
public static void main(String[] args) {
Person person = new Person();
person.setName("Vidhya");
person.setAge(30);
Advantages:
Definition
Example:
class A {
public void display() {
System.out.println("Class A");
}
}
class B extends A {
public void display() {
System.out.println("Class B");
}
}
class Trial {
public static void main(String[] args) {
A a = new A();
A b = new B();
Definition
Example:
class A {
void callme() {
System.out.println("Inside A's callme method");
}
}
class B extends A {
void callme() {
System.out.println("Inside B's callme method");
}
}
class DispatchDemo {
public static void main(String[] args) {
A obj; // Reference of type A
Definition
Method Overloading occurs when a class has multiple methods with the same name
but different parameters.
It is also known as compile-time (static) polymorphism.
Characteristics
The same method name can be used with:
1. Different numbers of parameters
2. Different data types of parameters
3. Different order of parameters
Overloading methods with different return types is not allowed.
During compilation, the compiler determines which method to call based on the type
and number of arguments passed.
Example:
class OverloadingDemo {
// Method with two integer parameters
void sum(int a, int b) {
System.out.println("Sum of (a+b) is:: " + (a + b));
}
Output
this Keyword
class Box {
int width;
Box(int width) {
this.width = width; // `this` refers to the instance variable
}
}
2. Calling Other Constructors: Used to call another constructor within the same
class.
class Box {
int width, height;
Box(int width) {
this(width, 10); // Calls the two-parameter constructor
}
Box(int width, int height) {
this.width = width;
this.height = height;
}
}
3. Returning the Current Object: Allows methods to return the current instance for
method chaining.
class Box {
int width;
Box setWidth(int width) {
this.width = width;
return this;
}
}
super Keyword
1. Accessing Parent Class Members: Access parent class fields or methods overridden in
the child class.
class Parent {
String name = "Parent";
}
class Child extends Parent {
String name = "Child";
void display() {
System.out.println(super.name); // Refers to the parent class field
System.out.println(name);
}
}
2. Calling Parent Class Methods: Used to invoke overridden methods in the parent class.
class Parent {
void display() {
System.out.println("Parent Method");
}
}
class Child extends Parent {
void display() {
super.display(); // Calls the parent class method
System.out.println("Child Method");
}
}
class Parent {
Parent(String message) {
System.out.println("Parent Constructor: " + message);
}
}
class Child extends Parent {
Child(String message) {
super(message); // Calls the parent class constructor
}
}
Key Differences
These keywords are essential for managing class hierarchies and handling object-specific
references in Java programming.
The static keyword in Java is primarily used for memory management. It allows variables and
methods to be shared across all instances of a class, meaning they belong to the class rather
than any particular object of the class. This is useful for creating constants or methods that
should be the same for every instance of the class.
Key Applications:
Variables
Methods
Blocks
Nested Classes
1. Shared Memory Allocation: Static variables and methods are allocated memory space
only once, shared by all instances of the class. This is useful for global states or shared
functionalities.
2. Accessible Without Object Instantiation: Static members can be accessed without
creating an instance of the class. This is ideal for utility functions and constants.
3. Associated with the Class: Static members are linked to the class itself, not to specific
objects. Changes to static members are reflected in all instances of the class.
4. Cannot Access Non-Static Members: Static methods cannot directly access non-static
members of the class as they are not associated with any particular instance.
5. Overloadable but Not Overridable: Static methods can be overloaded (same method
name with different parameters), but they cannot be overridden since they belong to
the class, not an object.
6. Access Before Instantiation: A static member can be accessed before any objects of its
class are created.
Static Blocks:
Static blocks are used for initialization of static variables and are executed once when the class
is loaded.
Example:
class Test {
static int a = 10;
static int b;
static {
System.out.println("Static block initialized.");
b = a * 4;
}
Static Variables:
Static variables are shared across all instances of the class, essentially acting as global variables
for that class.
Example:
class Test {
static int a = m1();
static {
System.out.println("Inside static block");
}
staticint m1() {
System.out.println("from m1");
return 20;
}
Static Methods:
Static methods are methods that belong to the class rather than any instance. They can only
access static variables and other static methods.
Restrictions:
1. Static methods can only directly call other static methods.
2. Static methods cannot access instance variables or methods directly.
3. Static methods cannot use this or super.
Example of Restrictions:
class Test {
static int a = 10;
int b = 20;
static void m1() {
a = 20;
System.out.println("from m1");
b = 10; // Error: Cannot access non-static field 'b'
m2(); // Error: Cannot call non-static method 'm2'
System.out.println(super.a); // Error: Cannot use 'super' in static context
}
void m2() {
System.out.println("from m2");
}
public static void main(String[] args) {
// Main method
}
}
1. Static Variables: For properties that are common to all instances, like a shared constant
or counter.
2. Static Methods: For utility functions that don’t require object-specific data.
Example:
class Student {
String name;
int rollNo;
static String cllgName;
static int counter = 0;
Student(String name) {
this.name = name;
this.rollNo = setRollNo();
}
Static int setRollNo() {
counter++;
return counter;
}
static void setCllg(String name) {
cllgName = name;
}
void getStudentInfo() {
System.out.println("name : " + name);
System.out.println("rollNo : " + rollNo);
System.out.println("cllgName : " + cllgName);
}}
public class StaticDemo {
public static void main(String[] args) {
Student.setCllg("XYZ");
Output:
name : Alice
rollNo : 1
cllgName : XYZ
name : Bob
rollNo : 2
cllgName : XYZ
Static Classes:
A class can only be declared static if it is a nested class. A static nested class does not require a
reference to the outer class and cannot access non-static members of the outer class.
Class Myclass {
private static String str = "Java programming language";
5. Class-Level Functionality: Static methods can define functionality that doesn’t depend
on object state.
Abstraction in Java
- Abstraction is a process of hiding the implementation details and showing only functionality to
the user.
- Another way, it shows only essential things to the user and hides the internal details,.
- for example, sending SMS where you type the text and send the message. You don't know the
internal processing about the message delivery.
Example:
abstract class salary
{
Int basic,da;
salary(int basic,int da) //Constructor
{
this.basic=basic;
this.da=da;
}
void greetings() //No abstract Method
{
System.out.println("Hello, Good morning all. I am Abstract Class");
}
abstract void ComputeSalary(); //Abstract Method
}
Output:
Interfaces in Java
Interface InterfaceName {
// Declare constant fields (public, static, final by default)
// Declare abstract methods (public by default)
void method1(); // abstract method
void method2(); // abstract method
}
Example:
interface A {
void display();
}
class B implements A{
public void display()
{
System.out.println("Hello");
}
}
class Interface_ex{
public static void main(String args[])
{
B obj = new B();
obj.display();
}}
Example:
interface A{
void display();
}
interface B{
void show();
}
class C implements A,B{
public void display() {
System.out.println("Display method");
}
public void show(){
System.out.println("show method");
}
}
class MB
{
public static void main(String args[])
{
C obj = new C();
obj.display();
obj.show();
}
}
Output:
Hello
Welcome
Interface inheritance
A class implements an interface, but one interface extends another interface.
Example:
interface A
{
void show1();
}
interface B //one interface extends another interface
{
void show2();
}
interface C extends A, B {
void show3();
}
class MB
{
public static void main(String args[])
{
demo obj = new demo();
obj.show1();
obj.show2();
obj.show3();
}
}
classMultiple_Inheritance{
public static void main(String args[]) {
Result R = new Result("Sutex",12,93,84);
R.display();
R.percent_cal();
}}
Output:
Name of Student: Sutex
Roll No. of Student: 12
Marks of Subject 1: 93
Marks of Subject 2: 84
Percentage: 88.0%