This document provides an overview of classes, functions, and access specifiers in Java. It discusses encapsulation, the different access specifiers (public, private, protected, default), scope and visibility rules for instance variables, class variables, and local variables. It also defines what functions are, how to define functions, and different types of functions including predefined and user-defined functions. The document is from a class at Blue Ridge Junior College covering chapters 7 and 8 on classes in Java and functions.
This document discusses encapsulation in object-oriented programming. Encapsulation involves enclosing data and functions together within a class and restricting access to that data. The document defines encapsulation and explains how it is used to hide implementation details and bind data to a single unit. It also discusses different access specifiers like public, private, protected, internal, and protected internal and how they control access to variables and methods within and outside of classes.
This document discusses encapsulation in object-oriented programming. Encapsulation involves enclosing data and functions together within a class and restricting access to that data. The document defines encapsulation and explains how it is used to hide implementation details and bind data to a single unit. It also discusses different access specifiers like public, private, protected, internal, and protected internal and how they control access to variables and methods within and outside of classes.
chapter 5 concepts of object oriented programmingWondimuBantihun1
The document discusses the basic concepts of object-oriented programming in Java, including objects, classes, abstraction, encapsulation, inheritance, and polymorphism. It provides examples of objects versus classes, creating objects, access modifiers, constructors, encapsulation with getter and setter methods, single inheritance, abstract classes and interfaces for abstraction, and method overloading and overriding for polymorphism.
The document discusses encapsulation in object-oriented programming, which involves hiding data within a class and only allowing it to be accessed via the class's methods, in order to protect the data from accidental or malicious changes and allow the internal implementation to change without affecting other code; it also covers the different access levels for classes, members, and packages using modifiers like public, private, and protected. Encapsulation provides benefits like flexibility to change a class's implementation without breaking dependent code and control over how data is accessed and stored within a class.
This document provides an overview of Java fundamentals including classes, objects, encapsulation, abstraction, inheritance, polymorphism and other core OOP concepts. Key points covered include:
- Classes contain variable declarations and method definitions while objects have state, behavior and identity.
- Encapsulation is achieved by declaring class variables as private and providing public get and set methods.
- Abstraction hides certain details and shows only essential information to the user using abstract classes and interfaces.
- Inheritance allows classes to extend functionality from other classes in a hierarchical manner to achieve code reuse.
- Polymorphism allows a single action to be performed in different ways depending on the object used.
Encapsulation is one of the fundamental principles of object-oriented programming that allows objects to hide their internal representation and behavior from other objects. It involves restricting access to components of a class, and allowing access to the class only through public methods. This allows for more secure and maintainable code by preventing accidental or malicious changes to internal data. Getters and setters are commonly used to access private fields in a controlled manner and can include additional logic. Encapsulation provides benefits like making fields read-only or write-only, and allowing classes to control their internal data representation without affecting other code.
The document discusses key concepts of object-oriented programming (OOP) including encapsulation, inheritance, polymorphism, and abstraction. It defines encapsulation as making fields private and providing public access methods. Inheritance allows classes to extend other classes, with types including simple, multilevel, hierarchical, and hybrid inheritance. The document also covers access specifiers like public, private, protected, and default and provides code samples to demonstrate their usage. Interfaces are described as similar to classes but containing only abstract methods and final fields, with classes implementing interfaces by providing method code.
This document discusses object-based programming concepts like instantiating objects, encapsulation, inheritance, polymorphism, and garbage collection. It provides examples of implementing a class with properties, constructors, and access modifiers. Key points covered include defining classes with methods and members, creating objects from classes, allowing subclasses to inherit features, and allowing objects to take different forms through polymorphism techniques like overriding and overloading.
This document discusses encapsulation in object-oriented programming. Encapsulation involves enclosing data and functions together within a class and restricting access to that data. The document defines encapsulation and explains how it is used to hide implementation details and bind data to a single unit. It also discusses different access specifiers like public, private, protected, internal, and protected internal and how they control access to variables and methods within and outside of classes.
This document discusses encapsulation in object-oriented programming. Encapsulation involves enclosing data and functions together within a class and restricting access to that data. The document defines encapsulation and explains how it is used to hide implementation details and bind data to a single unit. It also discusses different access specifiers like public, private, protected, internal, and protected internal and how they control access to variables and methods within and outside of classes.
chapter 5 concepts of object oriented programmingWondimuBantihun1
The document discusses the basic concepts of object-oriented programming in Java, including objects, classes, abstraction, encapsulation, inheritance, and polymorphism. It provides examples of objects versus classes, creating objects, access modifiers, constructors, encapsulation with getter and setter methods, single inheritance, abstract classes and interfaces for abstraction, and method overloading and overriding for polymorphism.
The document discusses encapsulation in object-oriented programming, which involves hiding data within a class and only allowing it to be accessed via the class's methods, in order to protect the data from accidental or malicious changes and allow the internal implementation to change without affecting other code; it also covers the different access levels for classes, members, and packages using modifiers like public, private, and protected. Encapsulation provides benefits like flexibility to change a class's implementation without breaking dependent code and control over how data is accessed and stored within a class.
This document provides an overview of Java fundamentals including classes, objects, encapsulation, abstraction, inheritance, polymorphism and other core OOP concepts. Key points covered include:
- Classes contain variable declarations and method definitions while objects have state, behavior and identity.
- Encapsulation is achieved by declaring class variables as private and providing public get and set methods.
- Abstraction hides certain details and shows only essential information to the user using abstract classes and interfaces.
- Inheritance allows classes to extend functionality from other classes in a hierarchical manner to achieve code reuse.
- Polymorphism allows a single action to be performed in different ways depending on the object used.
Encapsulation is one of the fundamental principles of object-oriented programming that allows objects to hide their internal representation and behavior from other objects. It involves restricting access to components of a class, and allowing access to the class only through public methods. This allows for more secure and maintainable code by preventing accidental or malicious changes to internal data. Getters and setters are commonly used to access private fields in a controlled manner and can include additional logic. Encapsulation provides benefits like making fields read-only or write-only, and allowing classes to control their internal data representation without affecting other code.
The document discusses key concepts of object-oriented programming (OOP) including encapsulation, inheritance, polymorphism, and abstraction. It defines encapsulation as making fields private and providing public access methods. Inheritance allows classes to extend other classes, with types including simple, multilevel, hierarchical, and hybrid inheritance. The document also covers access specifiers like public, private, protected, and default and provides code samples to demonstrate their usage. Interfaces are described as similar to classes but containing only abstract methods and final fields, with classes implementing interfaces by providing method code.
This document discusses object-based programming concepts like instantiating objects, encapsulation, inheritance, polymorphism, and garbage collection. It provides examples of implementing a class with properties, constructors, and access modifiers. Key points covered include defining classes with methods and members, creating objects from classes, allowing subclasses to inherit features, and allowing objects to take different forms through polymorphism techniques like overriding and overloading.
This document discusses the key concepts of object-oriented programming (OOP) including objects, classes, encapsulation, inheritance, polymorphism, and abstraction. It defines objects as instances of classes that have data fields and methods. Classes contain both data and functions and can have private, public, or protected members. Encapsulation binds data and functions into a class. Inheritance allows deriving new classes from existing ones. Polymorphism enables classes to provide different implementations of methods with the same name. Abstraction simplifies complexity by modeling appropriate classes for a problem.
Std 12 computer chapter 8 classes and object in java (part 2)Nuzhat Memon
Std 12 computer chapter 8 classes and objects in java (Part 2) by Nuzhat Memon
Variable Type (Instance Variable, Class Variable, Local Variable)
Accessing an instance variable and method using Dot notation
Accessing class variable and method using class name
Inheritance
Polymorphism (Method overloading and Method overridden)
Access Modifier or Visibility Modifier in java (4 p's Public Package Private and Private)
Accessor and Mutator
Composition and Aggregation
Constructor (special kind of method called automatically when a new object is created)
This document provides an overview of access specifiers and modifiers in Java/J2EE programming. It discusses class modifiers like public, abstract, and final. It covers access modifiers for class members like private, protected, and public. Non-access modifiers for members such as synchronized, transient, and abstract are also explained. The document reviews modifiers for inner classes and provides examples of class, interface, and method declarations. It describes implementing interfaces and the main method. Key points about determining access to class members and additional programming concepts are also summarized.
Inheritance allows reuse of properties and behaviors of an existing class when creating new classes. The existing class is called the base/parent class, while the new class is the derived/child class. The child class inherits all properties and behaviors of the parent class and can define additional properties and behaviors of its own. There are different types of inheritance like single, multilevel, multiple and hierarchical inheritance which define how properties and behaviors are inherited between parent and child classes.
The document discusses inheritance in object-oriented programming. It defines inheritance as a parent-child relationship between classes that allows sharing of behavior from the parent class to child classes. This code sharing enables reusability, which is an important aspect of OOP. Child classes can add new behavior or override existing behavior from the parent class. The document also discusses different types of inheritance like single, multiple, multi-level and hierarchical inheritance. It explains access modifiers like private, public, protected and default and how they control access to classes, methods and variables.
Inheritance in Java allows one class to acquire properties and behaviors of another class. This allows code reusability and method overriding to achieve runtime polymorphism. There are three types of inheritance: single, multilevel, and hierarchical. Access modifiers like private, default, protected, and public control the scope and accessibility of classes, methods, and fields. Method overriding provides a specific implementation of a method defined in the parent class.
This document discusses inheritance in object oriented programming. It covers key concepts of inheritance including derived classes inheriting behavior and attributes from base classes to promote code reuse. Specific topics covered include is-a relationships between classes, access control of inherited members, continuous inheritance where derived classes can act as base classes, and examples of inheritance hierarchies.
This is an intermediate conversion course for C++, suitable for second year computing students who may have learned Java or another language in first year.
This document discusses classes in Java. It covers defining a class, the elements of a class like methods and variables, memory allocation for classes, coding standards, access modifiers, encapsulation, inner classes, and examples. Key topics include how everything in Java is treated as an object, classes providing meaning to objects, and classes having logical but not physical existence until objects are created from them.
This document discusses inheritance in C++. It begins by defining inheritance as acquiring the properties of one class to another class. It then discusses the necessity of inheritance for reusability, expressing real-world relationships, and its transitive nature.
The document explains the relationship between a base class and derived class, with the derived class inheriting all capabilities of the base class. It provides an example of a derived class inheriting features A, B, and C from the base class and adding its own feature D.
The document outlines different types of inheritance including single, multi-level, multiple, hierarchical, and hybrid inheritance. It also discusses access control/visibility modes of public, private, and protected and how they
Know the difference between Inheritance and aggregation
Understand how inheritance is done in Java
Learn polymorphism through Method Overriding
Learn the keywords : super and final
Understand the basics of abstract class
The document provides an overview of object oriented programming concepts in SystemVerilog including classes, constructors, the "this" keyword, inheritance, polymorphism, overriding class members, the "super" keyword, data hiding and encapsulation. It discusses class properties and methods, static class members, class assignment, shallow and deep copy, and extern functions. Examples provided include an ones counter class and testbench.
This document discusses object-oriented programming concepts like classes, objects, methods, encapsulation, and visibility modifiers. It explains that a class defines the blueprint for an object, with data representing its state and methods representing its behavior. Methods can access instance data and parameters, while encapsulation involves hiding implementation details and controlling access via public, private, and other visibility modifiers. Getter and setter methods are used to access or modify private data.
The document discusses inheritance in object-oriented programming. It defines inheritance as a mechanism where a subclass inherits properties and behaviors from its parent superclass. The key points are:
- A subclass inherits attributes and methods from its superclass. The subclass can also define its own attributes and methods or override existing superclass methods.
- There are two types of inheritance - single inheritance where a subclass inherits from one superclass, and multiple inheritance which is not supported in Java.
- Access modifiers like public, private, protected determine which members of the superclass are accessible to subclasses. Private members cannot be accessed by subclasses.
- The extends keyword is used to create a subclass that inherits from an existing superclass. The subclass inherits all non
This chapter discusses inheritance, exceptions, and exception handling in Java. It covers inheritance relationships between superclasses and subclasses, overriding and calling superclass methods, abstract classes and methods, and composition. The chapter also examines Java's exception hierarchy and different types of exceptions. Finally, it explores exception handling techniques like try/catch blocks and throwing, rethrowing, and creating custom exceptions.
This document discusses key object-oriented programming concepts including encapsulation, inheritance, polymorphism, abstract classes, and interfaces. It provides examples of how encapsulation hides implementation details and inheritance allows classes to inherit properties from superclasses. Polymorphism allows objects to take on multiple forms through inheritance. Abstract classes cannot be instantiated directly but provide a common definition that concrete subclasses implement. Interfaces define behaviors for classes to implement but do not provide implementations.
Encapsulation is an object-oriented programming concept that binds together the data and functions that manipulate the data, and that keeps both safe from outside interference and misuse. It hides the internal representation of an object from outside code by only allowing access through public methods. This allows for changes to the implementation of the methods and attributes without affecting the outside code. Encapsulation is achieved by setting data as private and providing public getters and setters to access and modify the private data.
This document provides a guide to class member and local variable declarations in Java, including access modifiers like public, private, protected, and default, as well as other declarations like static, final, transient, synchronized, abstract, and volatile. It explains how and when to use each declaration type for class members versus local variables, and how anonymous objects and lambda expressions can access variables. The goal is to help programmers create scalable and loosely coupled Java programs by properly identifying declaration types. Suggestions and feedback are welcome in the comments.
This document discusses inheritance in object-oriented programming and Java. It introduces inheritance as a technique where a derived class inherits attributes and behaviors from a base class. A derived class automatically has all instance variables and methods of the base class. The document provides examples of how to define derived classes in Java that extend and override methods from a base class. It also discusses concepts like final classes that cannot be inherited from, and using the super constructor to initialize inherited attributes.
Main Java[All of the Base Concepts}.docxadhitya5119
This is part 1 of my Java Learning Journey. This Contains Custom methods, classes, constructors, packages, multithreading , try- catch block, finally block and more.
This document discusses the key concepts of object-oriented programming (OOP) including objects, classes, encapsulation, inheritance, polymorphism, and abstraction. It defines objects as instances of classes that have data fields and methods. Classes contain both data and functions and can have private, public, or protected members. Encapsulation binds data and functions into a class. Inheritance allows deriving new classes from existing ones. Polymorphism enables classes to provide different implementations of methods with the same name. Abstraction simplifies complexity by modeling appropriate classes for a problem.
Std 12 computer chapter 8 classes and object in java (part 2)Nuzhat Memon
Std 12 computer chapter 8 classes and objects in java (Part 2) by Nuzhat Memon
Variable Type (Instance Variable, Class Variable, Local Variable)
Accessing an instance variable and method using Dot notation
Accessing class variable and method using class name
Inheritance
Polymorphism (Method overloading and Method overridden)
Access Modifier or Visibility Modifier in java (4 p's Public Package Private and Private)
Accessor and Mutator
Composition and Aggregation
Constructor (special kind of method called automatically when a new object is created)
This document provides an overview of access specifiers and modifiers in Java/J2EE programming. It discusses class modifiers like public, abstract, and final. It covers access modifiers for class members like private, protected, and public. Non-access modifiers for members such as synchronized, transient, and abstract are also explained. The document reviews modifiers for inner classes and provides examples of class, interface, and method declarations. It describes implementing interfaces and the main method. Key points about determining access to class members and additional programming concepts are also summarized.
Inheritance allows reuse of properties and behaviors of an existing class when creating new classes. The existing class is called the base/parent class, while the new class is the derived/child class. The child class inherits all properties and behaviors of the parent class and can define additional properties and behaviors of its own. There are different types of inheritance like single, multilevel, multiple and hierarchical inheritance which define how properties and behaviors are inherited between parent and child classes.
The document discusses inheritance in object-oriented programming. It defines inheritance as a parent-child relationship between classes that allows sharing of behavior from the parent class to child classes. This code sharing enables reusability, which is an important aspect of OOP. Child classes can add new behavior or override existing behavior from the parent class. The document also discusses different types of inheritance like single, multiple, multi-level and hierarchical inheritance. It explains access modifiers like private, public, protected and default and how they control access to classes, methods and variables.
Inheritance in Java allows one class to acquire properties and behaviors of another class. This allows code reusability and method overriding to achieve runtime polymorphism. There are three types of inheritance: single, multilevel, and hierarchical. Access modifiers like private, default, protected, and public control the scope and accessibility of classes, methods, and fields. Method overriding provides a specific implementation of a method defined in the parent class.
This document discusses inheritance in object oriented programming. It covers key concepts of inheritance including derived classes inheriting behavior and attributes from base classes to promote code reuse. Specific topics covered include is-a relationships between classes, access control of inherited members, continuous inheritance where derived classes can act as base classes, and examples of inheritance hierarchies.
This is an intermediate conversion course for C++, suitable for second year computing students who may have learned Java or another language in first year.
This document discusses classes in Java. It covers defining a class, the elements of a class like methods and variables, memory allocation for classes, coding standards, access modifiers, encapsulation, inner classes, and examples. Key topics include how everything in Java is treated as an object, classes providing meaning to objects, and classes having logical but not physical existence until objects are created from them.
This document discusses inheritance in C++. It begins by defining inheritance as acquiring the properties of one class to another class. It then discusses the necessity of inheritance for reusability, expressing real-world relationships, and its transitive nature.
The document explains the relationship between a base class and derived class, with the derived class inheriting all capabilities of the base class. It provides an example of a derived class inheriting features A, B, and C from the base class and adding its own feature D.
The document outlines different types of inheritance including single, multi-level, multiple, hierarchical, and hybrid inheritance. It also discusses access control/visibility modes of public, private, and protected and how they
Know the difference between Inheritance and aggregation
Understand how inheritance is done in Java
Learn polymorphism through Method Overriding
Learn the keywords : super and final
Understand the basics of abstract class
The document provides an overview of object oriented programming concepts in SystemVerilog including classes, constructors, the "this" keyword, inheritance, polymorphism, overriding class members, the "super" keyword, data hiding and encapsulation. It discusses class properties and methods, static class members, class assignment, shallow and deep copy, and extern functions. Examples provided include an ones counter class and testbench.
This document discusses object-oriented programming concepts like classes, objects, methods, encapsulation, and visibility modifiers. It explains that a class defines the blueprint for an object, with data representing its state and methods representing its behavior. Methods can access instance data and parameters, while encapsulation involves hiding implementation details and controlling access via public, private, and other visibility modifiers. Getter and setter methods are used to access or modify private data.
The document discusses inheritance in object-oriented programming. It defines inheritance as a mechanism where a subclass inherits properties and behaviors from its parent superclass. The key points are:
- A subclass inherits attributes and methods from its superclass. The subclass can also define its own attributes and methods or override existing superclass methods.
- There are two types of inheritance - single inheritance where a subclass inherits from one superclass, and multiple inheritance which is not supported in Java.
- Access modifiers like public, private, protected determine which members of the superclass are accessible to subclasses. Private members cannot be accessed by subclasses.
- The extends keyword is used to create a subclass that inherits from an existing superclass. The subclass inherits all non
This chapter discusses inheritance, exceptions, and exception handling in Java. It covers inheritance relationships between superclasses and subclasses, overriding and calling superclass methods, abstract classes and methods, and composition. The chapter also examines Java's exception hierarchy and different types of exceptions. Finally, it explores exception handling techniques like try/catch blocks and throwing, rethrowing, and creating custom exceptions.
This document discusses key object-oriented programming concepts including encapsulation, inheritance, polymorphism, abstract classes, and interfaces. It provides examples of how encapsulation hides implementation details and inheritance allows classes to inherit properties from superclasses. Polymorphism allows objects to take on multiple forms through inheritance. Abstract classes cannot be instantiated directly but provide a common definition that concrete subclasses implement. Interfaces define behaviors for classes to implement but do not provide implementations.
Encapsulation is an object-oriented programming concept that binds together the data and functions that manipulate the data, and that keeps both safe from outside interference and misuse. It hides the internal representation of an object from outside code by only allowing access through public methods. This allows for changes to the implementation of the methods and attributes without affecting the outside code. Encapsulation is achieved by setting data as private and providing public getters and setters to access and modify the private data.
This document provides a guide to class member and local variable declarations in Java, including access modifiers like public, private, protected, and default, as well as other declarations like static, final, transient, synchronized, abstract, and volatile. It explains how and when to use each declaration type for class members versus local variables, and how anonymous objects and lambda expressions can access variables. The goal is to help programmers create scalable and loosely coupled Java programs by properly identifying declaration types. Suggestions and feedback are welcome in the comments.
This document discusses inheritance in object-oriented programming and Java. It introduces inheritance as a technique where a derived class inherits attributes and behaviors from a base class. A derived class automatically has all instance variables and methods of the base class. The document provides examples of how to define derived classes in Java that extend and override methods from a base class. It also discusses concepts like final classes that cannot be inherited from, and using the super constructor to initialize inherited attributes.
Similar to Chapter 7 & 8 Classes in Java and Functions.pdf (20)
Main Java[All of the Base Concepts}.docxadhitya5119
This is part 1 of my Java Learning Journey. This Contains Custom methods, classes, constructors, packages, multithreading , try- catch block, finally block and more.
it describes the bony anatomy including the femoral head , acetabulum, labrum . also discusses the capsule , ligaments . muscle that act on the hip joint and the range of motion are outlined. factors affecting hip joint stability and weight transmission through the joint are summarized.
This slide is special for master students (MIBS & MIFB) in UUM. Also useful for readers who are interested in the topic of contemporary Islamic banking.
Thinking of getting a dog? Be aware that breeds like Pit Bulls, Rottweilers, and German Shepherds can be loyal and dangerous. Proper training and socialization are crucial to preventing aggressive behaviors. Ensure safety by understanding their needs and always supervising interactions. Stay safe, and enjoy your furry friends!
A workshop hosted by the South African Journal of Science aimed at postgraduate students and early career researchers with little or no experience in writing and publishing journal articles.
A review of the growth of the Israel Genealogy Research Association Database Collection for the last 12 months. Our collection is now passed the 3 million mark and still growing. See which archives have contributed the most. See the different types of records we have, and which years have had records added. You can also see what we have for the future.
Strategies for Effective Upskilling is a presentation by Chinwendu Peace in a Your Skill Boost Masterclass organisation by the Excellence Foundation for South Sudan on 08th and 09th June 2024 from 1 PM to 3 PM on each day.
How to Add Chatter in the odoo 17 ERP ModuleCeline George
In Odoo, the chatter is like a chat tool that helps you work together on records. You can leave notes and track things, making it easier to talk with your team and partners. Inside chatter, all communication history, activity, and changes will be displayed.
How to Manage Your Lost Opportunities in Odoo 17 CRMCeline George
Odoo 17 CRM allows us to track why we lose sales opportunities with "Lost Reasons." This helps analyze our sales process and identify areas for improvement. Here's how to configure lost reasons in Odoo 17 CRM
This presentation includes basic of PCOS their pathology and treatment and also Ayurveda correlation of PCOS and Ayurvedic line of treatment mentioned in classics.
हिंदी वर्णमाला पीपीटी, hindi alphabet PPT presentation, hindi varnamala PPT, Hindi Varnamala pdf, हिंदी स्वर, हिंदी व्यंजन, sikhiye hindi varnmala, dr. mulla adam ali, hindi language and literature, hindi alphabet with drawing, hindi alphabet pdf, hindi varnamala for childrens, hindi language, hindi varnamala practice for kids, https://www.drmullaadamali.com
Introduction to AI for Nonprofits with Tapp NetworkTechSoup
Dive into the world of AI! Experts Jon Hill and Tareq Monaur will guide you through AI's role in enhancing nonprofit websites and basic marketing strategies, making it easy to understand and apply.
A Strategic Approach: GenAI in EducationPeter Windle
Artificial Intelligence (AI) technologies such as Generative AI, Image Generators and Large Language Models have had a dramatic impact on teaching, learning and assessment over the past 18 months. The most immediate threat AI posed was to Academic Integrity with Higher Education Institutes (HEIs) focusing their efforts on combating the use of GenAI in assessment. Guidelines were developed for staff and students, policies put in place too. Innovative educators have forged paths in the use of Generative AI for teaching, learning and assessments leading to pockets of transformation springing up across HEIs, often with little or no top-down guidance, support or direction.
This Gasta posits a strategic approach to integrating AI into HEIs to prepare staff, students and the curriculum for an evolving world and workplace. We will highlight the advantages of working with these technologies beyond the realm of teaching, learning and assessment by considering prompt engineering skills, industry impact, curriculum changes, and the need for staff upskilling. In contrast, not engaging strategically with Generative AI poses risks, including falling behind peers, missed opportunities and failing to ensure our graduates remain employable. The rapid evolution of AI technologies necessitates a proactive and strategic approach if we are to remain relevant.
1. Blue Ridge Junior College
Class XI – Computer Science
Ch 7 & 8 – Classes in Java and Functions
1
Blue
Ridge
Junior
College
2. Topics
• Encapsulation
• Access Specifiers
• Scope and Visibility Rules
• What are Functions?
• Defining Functions
• Classification of Functions
• Calling and Accessing Functions
• Function Overloading
• Objects as Parameters
• Constructors
2
Blue
Ridge
Junior
College
3. Encapsulation
• Encapsulation is one of the four fundamental OOP concepts
• Encapsulation in Java is a mechanism of wrapping the data
(variables) and code acting on the data (methods) together as
a single unit
• In encapsulation, the variables of a class will be hidden from
other classes, and can be accessed only through the methods
of their current class
• Therefore, it is also known as data hiding
3
Blue
Ridge
Junior
College
4. Access Specifiers
• The access to classes, constructors, methods and fields are
regulated using access modifiers
• A class can control what information or data can be accessible
by other classes
• Java provides a number of access modifiers to help you set the
level of access you want for classes as well as the fields,
methods and constructors in your classes
4
Blue
Ridge
Junior
College
5. Access Specifiers – cont.
• In Java, methods and data members of a class/interface can
have one of the following four access specifiers
• Visible to the package, the default. No modifiers are needed.
• Visible to the class only (private)
• Visible to the world (public)
• Visible to the package and all subclasses (protected)
5
Blue
Ridge
Junior
College
6. Access Specifiers – cont.
• Default Access Modifier - No Keyword
• If you do not use any modifier, it is treated as default
• Default access modifier means we do not explicitly declare an
access modifier for a class, field, method, etc.
• A variable or method declared without any access control
modifier is available to any other class in the same package
• The default modifier is accessible only within package
6
Blue
Ridge
Junior
College
7. Access Specifiers – cont.
• Default Access Modifier - No Keyword
• Example of default access modifier
//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();//Compile Time Error
obj.msg();//Compile Time Error
}
}
• In this example, we have created two packages pack and mypack.
We are accessing the A class from outside its package, since A class
is not public, so it cannot be accessed from outside the package
7
Blue
Ridge
Junior
College
8. Access Specifiers – cont.
• Private Access Modifier - Private
• Methods, variables, and constructors that are declared private
can only be accessed within the declared class itself
• Private access modifier is the most restrictive access level
• Using the private modifier is the main way that an object
encapsulates itself and hides data from the outside world
• Classes and interfaces cannot be private
8
Blue
Ridge
Junior
College
9. Access Specifiers – cont.
• Private Access Modifier - 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);//Compile Time Error
obj.msg();//Compile Time Error
}
}
• In this example, we have created two classes A and
Simple
• A class contains private data member and private
method
• We are accessing these private members from
outside the class, so there is compile time error
9
Blue
Ridge
Junior
College
10. Access Specifiers – cont.
• Public Access Modifier - Public
• A class, method, constructor, interface, etc. declared public can
be accessed from any other class
• Therefore, fields, methods, blocks declared inside a public class
can be accessed from any class
• However, if the public class we are trying to access is in a
different package, then the public class still needs to be imported
• Because of class inheritance, all public methods and variables of a
class are inherited by its subclasses
10
Blue
Ridge
Junior
College
11. Access Specifiers – cont.
• Public Access Modifier - 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();
}
}
• Output:Hello
11
Blue
Ridge
Junior
College
12. Access Specifiers – cont.
• Protected Access Modifier - Protected
• Variables, methods, and constructors, which are declared
protected in a superclass can be accessed only by the subclasses
in other package or any class within the package of the protected
members' class
• The protected access modifier cannot be applied to class and
interfaces. Methods, fields can be declared protected, however
methods and fields in a interface cannot be declared protected
12
Blue
Ridge
Junior
College
13. Access Specifiers – cont.
• Protected Access Modifier - 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();
}
}
• Output: Hello
• In this example, we have created the two packages pack and mypack
• The A class of pack package is public, so can be accessed from outside the package
• But msg method of this package is declared as protected, so it can be accessed from
outside the class only through inheritance
13
Blue
Ridge
Junior
College
14. Access Specifiers – cont.
• The following rules for inherited methods (for overriding) are
enforced:
• Methods declared public in a superclass also must be public in all
subclasses
• Methods declared protected in a superclass must either be
protected or public in subclasses; they cannot be private
• Methods declared private are not inherited at all, so there is no
rule for them
14
Blue
Ridge
Junior
College
15. Scope and Visibility Rules
• The scope of a variable defines the section of the code in
which the variable is visible
• Variable scope refers to the accessibility of a variable
• The lifetime of a variable refers to how long the variable exists
before it is destroyed
• As a general rule, variables that are defined within a block are
not accessible outside that block
15
Blue
Ridge
Junior
College
16. Scope and Visibility Rules – cont.
• The scope rules of a language are the rules that decide in
which part of the program a particular piece of code or data
item would be known and can be accessed
• The program part in which a particular piece of code or a data
value (e.g., variable) can be accessed is known as the
variable's Scope
• There are three types of variables:
• instance variables
• class variables
• local variables
16
Blue
Ridge
Junior
College
17. Scope and Visibility Rules – cont.
• Instance Variables
• Instance variables are those that are defined within a class itself
and not in any method or constructor of the class
• They are known as instance variables because every instance of
the class (object) contains a copy of these variables
• Instance variables are created when an object is created with
the use of the keyword 'new' and destroyed when the object is
destroyed
• The scope of instance variables is determined by the access
specifier that is applied to these variables
• The lifetime of these variables is the same as the lifetime of the
object to which it belongs
17
Blue
Ridge
Junior
College
18. Scope and Visibility Rules – cont.
• Instance Variables
public class Record{
public String name;// this instance variable is visible for any child class.
private int age;// this instance age variable is visible in Record class only.
public Record (String RecName)
{
name = RecName;
}
public void setAge(int RecSal)
{
age = RecSal;
}
public void printRec()
{
System.out.println("name : " + name ); // print the value for “name”
System.out.println("age :" + age); //prints the value for “age”
}
public static void main(String args[])
{
Record r = new Record("Ram");
r.setAge(23);
r.printRec();
}
}
• Output
name : Ram
age :23
18
Blue
Ridge
Junior
College
19. Scope and Visibility Rules – cont.
• Class Variables
• Class variables are those that are defined within a class itself
and not in any method or constructor of the class using the
keyword static
• Difference between non static instance variable and a static
class variable is that an instance variable is a separate copy and
the class variable is the same copy for all objects of the class
• Object not needed to reference a class variable
19
Blue
Ridge
Junior
College
20. Scope and Visibility Rules – cont.
• Local Variables
• A local variable is the one that is declared within a method or a
constructor (not in the header)
• The scope and lifetime are limited to the method itself
• In addition to the local variables defined in a method, we also
have variables that are defined in blocks like an if block and an
else block
• The scope and life is the same as that of the block itself
20
Blue
Ridge
Junior
College
21. Scope and Visibility Rules – cont.
• Local Variables
public class Dog
{
public void putAge()
{
int age = 0; //local variable
age = age + 6;
System.out.println("Dog age is : " + age);
}
public static void main(String args[]){
Dog d = new Dog();
d.putAge();
}
}
• Here, age is a local variable
• This variable is defined under putAge() method and its scope is
limited to this method only
21
Blue
Ridge
Junior
College
22. Scope and Visibility Rules – cont.
• Local Variables
• In Java, we can create nested blocks – a block inside another block.
• All the local variables in the outer block are accessible within the inner block but
vice versa is not true i.e., local variables within the inner block are not accessible
in the outer block
public static void main(String[] args)
{
int x;
//Begining of inner block
{
int y = 100;
x = 200;
System.out.println("x = "+x);
}
//End of inner block
System.out.println("x = "+x);
y = 200; //Error as y is not accessible in the outer block
}
}
• As you can see in the above program, an error is generated as the
variable ”y” is not visible in the outer block and therefore cannot be accessed
22
Blue
Ridge
Junior
College
23. Scope and Visibility Rules – cont.
• Formal Parameters or Argument variables
• These are the variables that are defined in the header of
constructor or a method
• The scope of these variables is the method or constructor in
which they are defined
• The lifetime of these variables is limited to the time for which the
method keeps executing
• Once the method finishes execution, these variables are
destroyed
23
Blue
Ridge
Junior
College
24. Scope and Visibility Rules – cont.
• Formal Parameters or Argument variables
public class Test
{
private int num;
public void method(int x)
{
num=x;
}
public static void main(String args[])
{
Test t = new Test();
t.method(5);
}
}
24
Blue
Ridge
Junior
College
25. What are Functions?
• A Java method or a function is a collection of statements that
are grouped together to perform an operation
• Technically, a function is a subprogram within a main program,
which processes data and returns a value
• Each function has a unique name with which it is called within
a program
• A method or function can be called (invoked) at any point in a
program simply by utilizing the method's / function’s name 25
Blue
Ridge
Junior
College
26. What are Functions? – cont.
• As stated earlier, each method has its own name. When that
name is encountered in a program, the execution of the
program branches to the body of that method
• When the method is completed, execution returns to the area
of the program code from which it was called, and the
program continues on to the next line of code
26
Blue
Ridge
Junior
College
27. Need for Functions
• When you start writing real programs, you
would realize that they can grow to many pages
of code
• A full-length program contains many pages of
code, and trying to find a specific part of the
program in all that code can be tough
• When programs get long, they also get harder
to organize and read
• To overcome this problem, professional
programmers break their programs down into
individual functions, each of which completes a
specific and well-defined task
27
Blue
Ridge
Junior
College
28. Need for Functions – cont.
• Using modular programming techniques, you can
break a long program into individual modules, each
of which performs a specific task
• When you break your program's modules down into
even smaller modules, you are using a top-down
approach to program design
• By using top-down programming techniques, you
can write any program as a series of small, easy-to-
handle tasks
• In Java, the basic unit for organizing code in a top-
down manner is the function
28
Blue
Ridge
Junior
College
29. Need for Functions – cont.
• Functions are time savers, in that they allow for the repetition
of sections of code without retyping the code
• In addition, functions can be saved and utilized again and
again in newly developed programs
• The use of methods will be our first step in the direction of
modular programming
29
Blue
Ridge
Junior
College
30. Defining Functions
• The general format of defining function in a java
class is as follows:
• [access specifier][static][return type] function-
name (formal parameters)
• access specifier: It defines the access type of the method. This
can be public, private, protected or default. By default, functions
have public access specifier
• static: The static keyword enables the function to be called
without creating an object
• return-type: The data type of the value returned by the method,
or void if the method does not return a value
30
Blue
Ridge
Junior
College
31. Defining Functions – cont.
• function-name: This is the name of the function
• formal parameters: The list of parameters - it is the type, order,
and number of parameters of a method. These are optional,
method may contain zero parameters. If there are no parameters,
you must use empty parentheses
• function body: The set of statements that would get executed
when the function is called.
31
Blue
Ridge
Junior
College
32. Defining Functions – cont.
• function-header: This is the first line which contains the access
specifier, return type, function name and list of parameters.
• formal signature: A method signature is written by using the
method name along with the parameters to be passed to the
method. Example of method signature: test(int a, int b)
32
Blue
Ridge
Junior
College
33. Defining Functions – cont.
• Naming a Method / Function
• Although a method name can be any legal identifier,
code conventions restrict method names
• By convention, method names should be a verb in
lowercase or a multi-word name that begins with a
verb in lowercase, followed by adjectives, nouns, etc.
• In multi-word names, the first letter of each of the
second and following words should be capitalized.
Here are some examples:
• run
• runFast
• getBackground
• getFinalData
33
Blue
Ridge
Junior
College
34. Defining Functions – cont.
• A method's declaration provides a lot of information about
the method to the compiler, the runtime system and to other
classes and objects
• Besides the name of the method, the method declaration
carries information such as the return type of the method, the
number and type of the arguments required by the method,
and what other classes and objects can call the method
34
Blue
Ridge
Junior
College
35. Classification of Functions
• A Java program is basically a set of classes
• A class is defined by a set of declaration statements
and methods or functions
• Java programming supports different types of
function as in User Defined Function (UDF)(A
function which is created by user so it is known as
user defined function) and also there are some
functions available within the Java packages that
provide some imperative support to the java
programmer for developing their programming logic
as well as their programming architecture
35
Blue
Ridge
Junior
College
36. Classification of Functions – cont.
• Predefined Functions
• The Java API or application programming interface is a collection
of software packages that programmers can use for graphics, user
interface, networking, sound, database, math, and much more
• It contains many methods that have already been written and
tested
• In order to use these specific methods in our program we have to
import the necessary libraries by adding them to our program
36
Blue
Ridge
Junior
College
37. Classification of Functions – cont.
• User Defined Functions
• Functions defined by the programmer within the program to use
it for a particular task
• User defined function is totally based on the user control
• When we create user define function name then we must
remember some special point that points are given below
• We cannot use any reserved keywords
• We can use the same function name for the different
numbers of types of arguments list
• So, we can overload our user-defined functions in our system
• The function name can only comprehend letters, numbers,
and the underscore (_)
• Function name must start with a letter
• The function names which cannot be exceed 128 characters
37
Blue
Ridge
Junior
College
38. Classification of Functions – cont.
• Functions are mostly used to produce some computational
output
• Actions inside a function may be like reading and displaying
some data values; assigning or modifying some existing
values; computing and returning a result for further use, etc.
• Out of all such actions, some operations like write or modify
can disturb or change the value of some already stored
member-data. Therefore, write or update operations are to
be treated very carefully and unrestricted public access
should not be allowed
• On the other hand, read or display operations are not
destructive, because read operations do not change data
values. So no access restriction will be necessary for such
operations
• Based on the operational side effects, functions can be
classified as either pure functions or impure functions
38
Blue
Ridge
Junior
College
39. Classification of Functions – cont.
• Pure Functions
• A pure function, when invoked, does not cause any change in the
state of an object, that means there will be no change in the
values of the object’s instance variables
• For example readData() or getData() functions can be treated as
pure functions as they do not change any existing data values
• Pure functions can safely be declared as public also
39
Blue
Ridge
Junior
College
40. Classification of Functions – cont.
• Pure Functions
• Code snippet for pure function:
class add
{
void sum(int a, int b)
{
int c = calc(a,b);
System.out.println(“The sum is” +c);
}
int calc(int a, int b)
{
int c=a+b;
return(c);
}
}
When a method contains a return statement, it is always the final
statement of that method, because no further statements in the
method will be executed once the return statement is executed
40
Blue
Ridge
Junior
College
41. Classification of Functions – cont.
• Impure Functions
• Impure functions, also called modifier functions, are those that
can cause a change of state in the object
• Values of the object’s instance variables get modified or changed
depending on the current state of the object on which the
function operates
• Such functions can cause some unwanted side effects if not
carefully controlled by the access-modifier
41
Blue
Ridge
Junior
College
42. Classification of Functions – cont.
• Impure Functions
• Demonstration of an Impure Function
public class ImpureFncTest
{
String name;
int accNo;
double accBalance;
double withdrawVal;
public double transaction(double balance, double withdraw)
{
if
( withdraw > balance) {System.out.println("Sorry !! Transaction Impossible.");}
else
{balance = balance - withdraw;System.out.println("Transaction Successful.");}
return balance
;}
public void show( double bal){
System.out.println ( "Balance Available : " + bal);}
public static void main()
{// manipulation of the first object
ImpureFncTest customer1 = new ImpureFncTest();//first object
customer1.name = " Anita Kar";
customer1.accNo = 8912;
customer1.accBalance = 123456.50;
customer1.withdrawVal = 5000.00;
System.out.println ( customer1.name + " -- Account No. :: " + customer1.accNo);customer1.accBalance =
customer1.transaction(customer1.accBalance,customer1.withdrawVal);customer1.
show(customer1.accBalance);
// manipulation of the second object
ImpureFncTest customer9 = new ImpureFncTest();//second object
customer9.name = " Kalyan Bhatt";
customer9.accNo = 13245;
customer9.accBalance = 3592.75;
customer9.withdrawVal = 4000.00;
System.out.println ( customer9.name + " -- Account No. :: " + customer9.accNo);customer9.accBalance =
customer9.transaction(customer9.accBalance,customer9.withdrawVal);customer9.
show(customer9.accBalance);
} }
42
Blue
Ridge
Junior
College
43. Classification of Functions – cont.
• Impure Functions
• In this example, transaction (double, double) is an impure
function, because it causes a change in the object’s state by
changing the value of the Balance Available
43
Blue
Ridge
Junior
College
44. Classification of Functions– cont.
• Function can also be classified as follows depending upon the
function definition:
• Function which does not have argument or a return type
• Function which has an argument but no return type
• Function which has no argument but has a return type
• Function which has both an argument and return type
44
Blue
Ridge
Junior
College
45. Classification of Functions – cont.
• To understand this concept, we need to first cover returning
values from a function
• A method returns to the code that invoked it when it
• completes all the statements in the method,
• reaches a return statement, or
• throws an exception (covered later),
whichever occurs first
You declare a method's return type in its method declaration.
Within the body of the method, you use the return statement
to return the value.
45
Blue
Ridge
Junior
College
46. Classification of Functions – cont.
• Any method declared void doesn't return a value. It does not
need to contain a return statement, but it may do so
• In such a case, a return statement can be used to branch out
of a control flow block and exit the method and is simply
used like this:
• return;
• If you try to return a value from a method that is
declared void, you will get a compiler error.
• Any method that is not declared void must contain
a return statement with a corresponding return value, like
this:
• return returnValue;
• The data type of the return value must match the method's
declared return type; you can't return an integer value from a
method declared to return a boolean
46
Blue
Ridge
Junior
College
47. Classification of Functions – cont.
• Function which does not have argument or a return type
• Such functions do not have any argument and the return type is
void as the function only performs activities like computation
and printing
class ABC
{
void add()
{
int a=10;
int b=20;
int c=a+b;
System.out.println(c);
}
}
The void keyword allows us to create methods which do not return a value 47
Blue
Ridge
Junior
College
48. Classification of Functions – cont.
• Function which has an argument but no return type
• Such functions may have single or multiple arguments and
return nothing
class ABC
{
void add(int a, int b)
{
int c=a+b;
System.out.println(c);
}
}
• When passing arguments or parameters to a method, it should
be in the same order as their respective parameters in the
method specification
48
Blue
Ridge
Junior
College
49. Classification of Functions – cont.
Function which has no argument but has a return type
Such functions do not have any argument but return a value
using the return keyword
class ABC
{
int add()
{
int a=10;
int b=20;
int c=a+b;
return c;
}
} 49
Blue
Ridge
Junior
College
50. Classification of Functions – cont.
Function which has both an argument and return type
class ABC
{
int add(int a, int b)
{
int c=a+b;
return c;
}
}
50
Blue
Ridge
Junior
College
51. Calling and Accessing Functions
• Methods don't do anything until you call them into action
• The process of method calling is simple. When a program
invokes a method, the program control gets transferred to the
called method
• This called method then returns control to the caller in two
conditions, when −
• the return statement is executed.
• it reaches the method ending closing brace
51
Blue
Ridge
Junior
College
52. Calling and Accessing Functions
• The main() function gets executed first and then the other
functions are called
• All functions contained within the main() function are called
sub-functions
• A function can be called in two ways depending upon the
main() function
• Functions that are within the same class as the main()
method:
• In this case, the function can be directly called by the main()
method without needing an object to do so
52
Blue
Ridge
Junior
College
53. Calling and Accessing Functions
• Example:
public class ExampleMinNumber {
public static void main(String[] args) {
int a = 11;
int b = 6;
int c = minFunction(a, b);
System.out.println("Minimum Value = " + c);
}
/** returns the minimum of two numbers */
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}
53
Blue
Ridge
Junior
College
54. Calling and Accessing Functions
• Functions that are in a different class from the class with the main() method
• In this case, the function can be called by the main() method in two ways:
• If the method is static, it can be called using the classname and the dot operator
class Student
{
int rollno;
static String college = "ITS";
static void change()
{
college = "BBDIT";
}
public static void main(String args[])
{
change(); //main of the same class
}
} //end of class Student
class Test
{
public static void main(String args[])
{
Student.change(); //calling function of another class
}
}
54
Blue
Ridge
Junior
College
55. Calling and Accessing Functions
• If the method is non static, then we create an object and call the method using the dot operator
on the object
class Student1{
int rollno;
String name;
String college = "ITS";
Student1(int r, String n)
{
rollno = r;
name = n;
}
void display ()
{
System.out.println(rollno+" "+name+" "+college);
}
}// end of class Student1
class Test1
{
int a=5;
public static void main(String args[])
{
Student1 s = new Student1 (111,"Karan"); //creating object for Student1 class
s.display(); //calling method of another class
}
}
55
Blue
Ridge
Junior
College
56. Function Overloading
• Function Overloading is a feature that allows a class to have
two or more methods having same name, if their argument
lists are different
• Overloading always occurs in the same class
• Method overloading is one of the ways through which Java
supports polymorphism
• Method overloading can be done by changing number of
arguments or by changing the data type of arguments
• If two or more methods have the same name and same
parameter list but differ in return type, they are not said to
be overloaded method
56
Blue
Ridge
Junior
College
57. Function Overloading – cont.
• When an overloaded method is invoked, Java uses the type
and/or number of arguments as its guide to determine which
version of the overloaded method to actually call
• Thus, overloaded methods must differ in the type and/or
number of their parameters
• When Java encounters a call to an overloaded method, it
simply executes the version of the method whose parameters
match the arguments used in the call
57
Blue
Ridge
Junior
College
58. Function Overloading – cont.
• Need for Function Overloading
• Using the concept of function overloading, a family of functions
can be designed , with one function name but different
parameter lists
• This is how java supports polymorphism using function
overloading, "one interface, multiple methods paradigm‘
• One benefit of overloading is that you can access related
methods by using common name
• Function overloading avoids coding error if there are different
methods names and a wrong method is coded by the
programmer
58
Blue
Ridge
Junior
College
59. Function Overloading – cont.
• Changing number of arguments
class Adder
{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}
}
• In this example, we have created two methods, first add()
method performs addition of two numbers and second add()
method performs addition of three numbers
• In this example, we have creating static methods so that we
don't need to create instance for calling methods
59
Blue
Ridge
Junior
College
60. Function Overloading – cont.
• Changing data type of arguments
class Adder
{
static int add(int a, int b)
{
return a+b;
}
static double add(double a, double b)
{
return a+b;
}
}
class TestOverloading
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}
}
• In this example, we have created two methods that differs in data
type
• The first add method receives two integer arguments and second
add method receives two double arguments
60
Blue
Ridge
Junior
College
61. Recursive Function
• A function designed in such a way that it calls itself in its body
is called Recursive Function
61
Blue
Ridge
Junior
College
62. Objects as Parameters
• We can pass object of any class as parameter to a
method in Java
• For example, consider the following program:
class Rectangle {
int length;
int width;
Rectangle(int l, int b) {
length = l;
width = b;
}
void area(Rectangle r1) {
int areaOfRectangle = r1.length * r1.width;
System.out.println("Area of Rectangle : "
+ areaOfRectangle);
}
}
class RectangleDemo {
public static void main(String args[]) {
Rectangle r1 = new Rectangle(10, 20);
r1.area(r1);
}
}
Output of the program :
Area of Rectangle : 200
62
Blue
Ridge
Junior
College
63. Objects as Parameters – cont.
• We can access the instance variables of the object passed
inside the called method
• Like area = r1.length * r1.width
• It is a good practice to initialize instance variables of an object
before passing object as parameter to the method. Otherwise
it will take the default initial values
63
Blue
Ridge
Junior
College
64. Objects as Parameters – cont.
• Call by Value and Call by Reference
• Before we look into what the terms call by value and call by reference mean, let
us look at two simple programs and examine their output:
class CallByValue {
public static void main ( String[] args ) {
int x =3;
System.out.println ( "Value of x before calling increment() is "+x);
increment(x);
System.out.println ( "Value of x after calling increment() is "+x);
}
public static void increment ( int a ) {
System.out.println ( "Value of a before incrementing is "+a);
a= a+1;
System.out.println ( "Value of a after incrementing is "+a);
}
}
The output of this program would be:
Value of x before calling increment() is 3
Value of a before incrementing is 3
Value of a after incrementing is 4
Value of x after calling increment() is 3
64
Blue
Ridge
Junior
College
65. Objects as Parameters – cont.
• As is evident from the output, the value of x has remain unchanged, even though it
was passed as a parameter to the increment() method
• And now, we move on to the second program, where we will make use of class
Number that contains a single instance variable x
class Number {
int x;
}
class CallByReference {
public static void main ( String[] args ) {
Number a = new Number();
a.x=3;
System.out.println("Value of a.x before calling increment() is "+a.x);
increment(a);
System.out.println("Value of a.x after calling increment() is "+a.x);
}
public static void increment(Number n) {
System.out.println("Value of n.x before incrementing x is "+n.x);
n.x=n.x+1;
System.out.println("Value of n.x after incrementing x is "+n.x);
}
}
This program would give the following output
Value of a.x before calling increment() is 3
Value of n.x before incrementing x is 3
Value of n.x after incrementing x is 4
Value of a.x after calling increment() is 4
65
Blue
Ridge
Junior
College
66. Objects as Parameters – cont.
• In the first program, the change made to the variable a inside
the increment() method had no effect on the original variable
x that was passed as an argument
• On the other hand, in the second program, changes made to
the variable x that was a part of the object in the increment()
method had an effect on the original variable ( the object
which contained that integer variable) that was passed as an
argument
• The difference lies in the type of the variable that was passed
as an argument
• int is a primitive data type while Number is a reference data
type
• Primitive data types in Java are passed by value while
reference data types are passed by reference
66
Blue
Ridge
Junior
College
67. Objects as Parameters – cont.
• What we mean by passing a variable by value is that the
value held in the variable that is passed as an argument
is copied into the parameters that are defined in the
method header
• That is why changes made to the variable within the
method had no effect on the variable that was passed
• On the other hand, when objects are passed, the object
itself is passed
• No copy is made. Therefore changes made to the object
within the method increment() had an effect on the
original object
67
Blue
Ridge
Junior
College
68. Objects as Parameters – cont.
• The following figure illustrate call be reference and call by
value
68
Blue
Ridge
Junior
College
69. Objects as Parameters – cont.
• The concept of call by reference can be better understood if
one tries to look into what a reference actually is and how a
variable of a class type is represented
• When we declare a reference type variable, the compiler
allocates only space where the memory address of the object
can be stored. The space for the object itself isn't allocated
• The space for the object is allocated at the time of object
creation using the new keyword
• A variable of reference type differs from a variable of a
primitive type in the way that a primitive type variable holds
the actual data while a reference type variable holds the
address of the object which it refers to and not the actual
object. 69
Blue
Ridge
Junior
College
70. Static Members and Functions
• static is a Java keyword. It can be applied to a field, a method
or an inner class
• If you declare any variable as static, it is known as a static
variable
• The static keyword in Java means that the variable or
function is shared between all instances of that class as it
belongs to the type, not the actual objects themselves
• The static variable gets memory only once in class area at the
time of class loading
• So if you have a variable: private static int i = 0; and you
increment it (i++) in one instance, the change will be
reflected in all instances. i will now be 1 in all instances 70
Blue
Ridge
Junior
College
71. Static Members and Functions –
cont.
• Java static variable
• It is a variable which belongs to the class and not to object(instance)
• Static variables are initialized only once, at the start of the execution.
These variables will be initialized first, before the initialization of any
instance variables
• A single copy to be shared by all instances of the class
• A static variable can be accessed directly by the class name and
doesn’t need any object
• Syntax : <class-name>.<variable-name>
71
Blue
Ridge
Junior
College
72. Static Members and Functions –
cont.
• Java Static Functions
• It is a method which belongs to the class and not to
the object(instance)
• A static method can access only static data. It can not access non-
static data (instance variables)
• A static method can call only other static methods and can not
call a non-static method from it.
• A static method can be accessed directly by the class name and
doesn’t need any object
• Syntax : <class-name>.<method-name>
72
Blue
Ridge
Junior
College
73. Static Members and Functions –
cont.
• Understanding problem without static variables
class Student{
int rollno;
String name;
String college="ITS";
}
• Suppose there are 500 students in my college, now all
instance data members will get memory each time when
object is created
• All student have its unique rollno and name so instance data
member is good
• Here, college refers to the common property of all objects
• If we make it static, this field will get memory only once.
73
Blue
Ridge
Junior
College
74. Static Members and Functions –
cont.
class Student{
int rollno;
String name;
static String college ="IIT";
Student(int r,String n){
rollno = r;
name = n;
}
void display ()
{
System.out.println(rollno+" "+name+" "+college);
}
public static void main(String args[]){
Student s1 = new Student(111,“Raj");
Student s2 = new Student(222,“Shubham");
s1.display();
s2.display();
}
}
Output:
111 Raj IIT
222 Shubham IIT
74
Blue
Ridge
Junior
College
75. Static Members and Functions –
cont.
• Difference between Static variables and Instance variables:
• Static variables and instance variables both are member
variables because they are both associated with a specific class,
but the difference between them is Static variables has only one
copy that is shared by all the different objects of a class,
whereas every object has its own personal copy of an instance
variable
• So, instance variables across different objects can have different
values whereas static variables across different objects can have
only one value
• Both are declared at class level outside any method
• Static variables are also called class variables
75
Blue
Ridge
Junior
College
76. What are Constructors?
• A constructor in Java is a block of code similar to a method
that is called when an instance of an object is created
• It is a special method that is used to initialize a newly created
object
• Java constructor is invoked at the time of object creation
• It constructs the values i.e. provides data for the object that is
why it is known as constructor
76
Blue
Ridge
Junior
College
77. What are Constructors – cont.
• Key differences between a constructor and a method
• A constructor doesn’t have a return type (not even void) since
the basic aim is to place the value in the object. If we write the
return type for the constructor then that constructor will be
treated as ordinary method
• The name of the constructor must be the same as the name of
the class
• Constructor definitions should not be static as constructors will
be called each and every time, whenever an object is created
77
Blue
Ridge
Junior
College
78. What are Constructors – cont.
• Unlike methods, constructors are not considered members of a
class
• A constructor is called automatically when a new instance of an
object is created
78
Method Constructor
Method can be any user
defined name
Constructor must be class
name
Method should have return
type
It should not have any return
type (even void)
Method should be called
explicitly either with object
reference or class reference
It will be called automatically
whenever object is created
Method is not provided by
compiler in any case
The java compiler provides a
default constructor if we do
not have any constructor
Blue
Ridge
Junior
College
79. Need for Constructors
• It can be cumbersome to initialize all variables in a call each
time an instance of a class in created
• Constructors are mainly created for initializing the object
• Initialization is a process of assigning user defined values at
the time of allocation of memory space
• An advantage of constructors in Java is it eliminates placing
the default values
79
Blue
Ridge
Junior
College
80. Need for Constructors – cont.
• Whenever we create an object of any class, memory is
allocated memory for all the data members and their
values are initialized to their default values
• To eliminate these default values by user defined values
we use constructor
80
Blue
Ridge
Junior
College
81. Constructor Example
class Programming
{ //constructor method
Programming()
{
System.out.println("Constructor method called.");
}
public static void main(String[] args)
{
Programming object = new Programming(); //creating object
}
}
81
Blue
Ridge
Junior
College
82. Types of Constructors
• Based on creating objects in Java, constructor are classified in
two types. They are:
• Default or no argument Constructor
• Parameterized Constructor
82
Blue
Ridge
Junior
College
83. Types of Constructors – cont.
Default or no argument Constructor
• A constructor that has no parameter is known as default
constructor
• If we do not define a constructor in a class, then compiler
creates default constructor(with no arguments) for the class
• If we write a constructor with arguments or no-argument then
compiler does not create default constructor
Default constructor provides the default values to the object like
0, null etc. depending on the type
83
Blue
Ridge
Junior
College
84. Types of Constructors – cont.
• Example of default constructor
• In this example, we are creating the no-argument constructor in
the Bike class
• It will be invoked at the time of object creation
class Bike
{
Bike()
{
System.out.println("Bike is created");
}
public static void main(String args[])
{
Bike b=new Bike ();
}
}
84
Blue
Ridge
Junior
College
85. Types of Constructors – cont.
• If there is no constructor in a class, compiler automatically
creates a default constructor
• The default constructor is a constructor that the Java
compiler adds to your code if no explicit constructor is
available
• If you have added your own constructor (no matter whether
it's without parameters or with parameters) the compiler will
not add the default constructor in this case
85
Blue
Ridge
Junior
College
86. Types of Constructors – cont.
• Parameterized Constructor
• A constructor that has parameters is known as parameterized
constructor
• If we want to initialize fields of the class with your own values,
then use parameterized constructor
• This type of constructor accepts parameters and initializes the
data members based on the arguments passed to it
• A parameter is a variable in a method definition. When a method is
called, the arguments are the data you pass into the method's
parameters
public void MyMethod(String myParam) { }
...
String myArg1 = "this is my argument"; myClass.MyMethod(myArg1);
86
Blue
Ridge
Junior
College
87. Types of Constructors – cont.
• Example of parameterized constructor
class Student4{
int id;
String name;
Student4(int i,String n){
id = i;
name = n;
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[]){
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
• In this example, we have created the constructor of Student class that has two parameters
• We can have any number of parameters in the constructor
87
Blue
Ridge
Junior
College
88. Constructor Overloading
• Constructor overloading is a technique in Java in which a class
can have any number of constructors that differ in parameter
lists
• Like methods, we can overload constructors for creating
objects in different ways
• Compiler differentiates constructors on the basis of numbers
of parameters, types of the parameters and order of the
parameters
88
Blue
Ridge
Junior
College
89. Constructor Overloading – cont.
• Example of Constructor Overloading
class Student5{
int id;
String name;
int age;
Student5(int i,String n){
id = i;
name = n;
}
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
public static void main(String args[]){
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}
89
Blue
Ridge
Junior
College
90. Constructor Overloading – cont.
class Demo{
int value1;
int value2;
Demo(){
value1 = 10;
value2 = 20;
System.out.println("Inside 1st Constructor");
}
Demo(int a){
value1 = a;
System.out.println("Inside 2nd Constructor");
}
Demo(int a,int b){
value1 = a;
value2 = b;
System.out.println("Inside 3rd Constructor");
}
public void display(){
System.out.println("Value1 === "+value1);
System.out.println("Value2 === "+value2);
}
public static void main(String args[]){
Demo d1 = new Demo();
Demo d2 = new Demo(30);
Demo d3 = new Demo(30,40);
d1.display();
d2.display();
d3.display();
}
}
90
Output
Blue
Ridge
Junior
College