Download presentation
Presentation is loading. Please wait.
1
Java Basics Classes and Objects
2
Topics To Be Covered Objectives Classes and Objects Wrapper Classes
Inner Classes Nested Classes Command Line Arguments Static Members Composition Summary
3
Objectives At the end of this course, you will be able to:
Define and use Classes and Objects Define and use Wrapper Classes Use Command Line Arguments Define and use Static variables. Static methods and Static block
4
Classes and Objects
5
Classes and Objects Concept of Class
A class is a description of an object having properties (attributes) and behavior (operations) An object is an instance of a class name rollNo 1001 Mary 1002 Jane e g. Mary is an object of Student class Jane is an object of Student class
6
Data Members / Instance variables (State)
Classes and Objects Constituents of a Class public class Student { private int rollNo; private String name; Student(){ //initialize data members } Student(String nameParam){ name - nameParam; public int getrollNo () { return rollNo; Data Members / Instance variables (State) Constructor Method (Behavior) The main method may or may not be present depending on whether the class is a starter class Naming Convention- Class Name: First letter Capital
7
Classes and Objects JAVA program consist piece of code called Classes.
Classes include Methods that perform task and return Information when they complete them. Most JAVA programmers take advantage of rich collection of existing classes in the JAVA class libraries.
8
Default is NOT a keyword in Java
Classes and Objects Access Modifiers Four Access Modifiers: private protected public default Data members are always kept private - Accessible only within the class The methods which expose the behavior of the object are kept public - However, we can have helper methods which are private Default is NOT a keyword in Java
9
Access Modifiers Public Keyword: A class may be declared with the modifier public, in which case that class is visible to all classes everywhere. No Keyword: If a class has no modifier (the default, also known as package-private), it is visible only within its own package (packages are named groups of related classes. Private Keyword: The private modifier specifies that the member can only be accessed in its own class. Protected Keyword: The protected modifier specifies that the member can only be accessed within its own package (as with package-private).
10
Access Modifiers The following table shows the access to members permitted by each modifier. Modifier Class Package Subclass World Public Y Protected N No modifier Private
11
Classes and Objects Concept of Object JAVA OBJECTS:
In the real world every thing maybe consider as object; a person is an object, a building all are objects. Programming language object has same characteristics as Real life object. Creating objects of a class: Objects are created dynamically using the new keyword. aCircle and bCircle refer to Circle objects
12
Classes and Objects Concept of Object aCircle = new Circle() ;
bCircle = new Circle() ;
13
Classes and Objects Creating Objects
The new operator creates an object and returns a reference Memory allocation of objects happens in the heap area Reference returned can be stored in reference variable obj1 is a reference variable New keyword creates an object and returns a reference obj1 obj2 Reference variable rollNo name Actual object Student obj1; obj1 = new Student ( ) : Or Student obj2 = new Student ( ) :
14
Classes and Objects Basic Syntax of class Definition class ClassName {
[fields declaration] [methods declaration] }
15
Classes and Objects Bare bone class – no fields, no methods
public class Circle { // my circle class }
16
Classes and Objects Adding Fields: Class Circle with fields
public class Circle { public double x, y; // centre coordinate public double r; // radius of the circle } The fields (data) are also called the instance variables.
17
Classes and Objects Adding Methods
A class with only data fields has no life. Objects created by such a class cannot respond to any messages. Methods are declared inside the body of the class but immediately after the declaration of data fields. The general form of a method declaration is: type MethodName (parameter-list) { Method-body; }
18
Classes and Objects Example code class Student { private int rollNo;
private String name; public String getName() { // Getter method return name; } public void setName(String name) { // Setter method this.name = name; public int getRollNo() { // Getter method return rollNo; public void setRollNo(int rollNo) { // Setter method this. rollNo = rollNo; } }
19
Classes and Objects Example code public class Demo{
public static void main( string[] args ) { Student s1; // Creating Reference variable s1= new Student(); // Creating actual object s1.setRollNo(347); // Calling setter method sl.setName(“Ajay"); // Calling setter Method System.out.println(’Roll No : “ + s1.getRollNo()) ; // Calling getter method System.out.println(“Name : " + sl.getName()); }
20
Classes and Objects Constructor
Constructors are special methods used to initialize a newly created object They are called just after memory is allocated for an object They initialize object data members with required values at the time of object creation It is not mandatory to write a constructor for each class A constructor Has the same name as that of the class Doesn't have any return type May or may not have parameters (arguments) If a class does not have constructor then the default constructor is provided In the absence of a user defined constructor, the compiler initializes member variables to its default values Numeric data types are set to 0 Char data types are set to null character (‘\0') Reference variables are set to null
21
Classes and Objects Example code class Student { private int rollNo;
private String name; public Student () { // Constructor without Parameter rollNo - 347; name = "Ajay"; } public Student (int rollNo, String name ) { // Parameterized Constructor this.rollNo = rollNo; this.name = name; public void printData() { // Method to Print object details System.out.println("Roll No : " + rollNo ); System.out.println("Name : " + name );
22
Classes and Objects Example code public class Demo{
public static void main( String[ ] args ) { // Calling constructor without parameter Student si = new Student(); si. print DataQ; // Calling Parameterized Constructor Student s2 = new Student(348,'Vijay"); sZ.printDataQ; }
23
Classes and Objects Lifetime of Objects
Student obj1 = new Student(); Student obj2 = new student(); obj1 1 2 obj2 Heap ► Both Student objects now live on the heap References: 2 Objects : 2 References: 3 Student obj3 = obj2; obj1 1 2 obj3 obj2 Heap
24
This object can be garbage collected
Classes and Objects Lifetime of Objects obj3 obj1 1 2 obj2 Heap obj3 = obj1; References: 3 Objects : 2 Active References : 2 Null References : 1 Reachable Objects : 1 Abandoned objects : 1 obj2 = null; obj1 1 2 obj3 obj2 Heap This object can be garbage collected Null Reference
25
Classes and Objects Garbage Collection
In C/C++, it is the programmer’s responsibility to de-allocate the dynamically allocated memory using the free() or delete In Java, JVM automatically de-allocates memory using component known as Garbage Collector An object which is not referred by any reference variable is removed from memory by the Garbage Collector. This process is known as Garbage Collection Primitive data types are not objects and cannot be directly be handled by Garbage Collector
26
Classes and Objects Scope of Variables
Instance Variables (also called Member Variables) Declared inside a class Outside any method or constructor Belong to the object Stored in heap area as a part of object Lifetime depends on the lifetime of object Local Variables (also called Stack Variables) Declared inside a method Method parameters are also local variables Stored in the program stack along with method calls and live until the call ends
27
Classes and Objects Scope of Variables
Type Default Value boolean False byte (byte) 0 short (short) 0 int long 0L char \u0000 float 0.0f double 0.0d object reference null If instance variables are not initialized explicitly, then they are initialized with default values, based on the type of the variable Local variables are not initialized by default
28
Classes and Objects Scope of Variables
class Student{ private 1 nt rollNo; private String name; public void display (int z){ int x = z + 10; } rollNo and name are instance variables to be stored in the heap Z and x are local variables to be stored in the stack
29
Wrapper Classes
30
Wrapper Classes Java treats objects differently from variables of Primitive types Some times we need to treat int, char, float values as Objects Java provides Wrapper Classes for each primitive type which wraps the value as an Object Converting from primitive to wrapper class is called as Boxing Converting from wrapper class to primitive is called as Unboxing Integer intobj = new Integer (575); int i = intobj.intValue( );
31
Constructor Arguments
Wrapper Classes Primitive Type Wrapper Class Constructor Arguments byte Byte byte or String short Short short or String int Integer int or String long Long long or String float Float float, double or String double Double double or String char Character boolean Boolean boolean or String
32
Wrapper Classes Wrapper classes have a lot of useful methods Examples:
A common translation is converting a string to a numeric type such as an int Example: Character.toLowerCase ( ch ) Character.is Letter ( ch ) String s = “65000”; int i = Integer.parseInt(s);
33
Wrapper Classes Autoboxing Feature
Auto-boxing and Auto-Unboxing enables the primitive types to be converted into respective wrapper objects and vice-versa The automatic transformation of primitive type (int, float, double etc.) into their object equivalents or wrapper type (Integer, Float, Double, etc) Is known as Autoboxing. During assignment or calling of constructor, the automatic transformation of wrapper types into their primitive equivalent is known as Unboxing. Conversion of int into Integer int value = 25; Integer intObj = value; // Auto Boxing int newValue = intObj; // Auto Unboxing
34
Wrapper Classes Example Code public class wrapperDemo {
public static void main(String[] args) { String number = "124"; //Converting String to Primitive Type int n = Integer.parselnt(number); System.out.println("Value of n = " + n); //Converting Primitive Type to Wrapper class Object (AutoBoxing ) Integer i = n; System.out.println("Value of i = " + i); }
35
Inner Classes
36
Inner Classes Java inner class or nested class is a class i.e. declared inside the class or interface. We use inner classes to logically group classes and interfaces in one place so that it can be more readable and maintainable. Additionally, it can access all the members of outer class including private data members and methods.
37
Inner Classes Syntax class Java_Outer_class{ //code
class Java_Inner_class{ //code } }
38
Nested Classes
39
Nested Classes There are two types of nested classes.
Non-static nested class(inner class) a)Member inner class b)Annomynous inner class c)Local inner class Static nested class
40
Nested Classes Example class TestMemberOuter1{ private int data=30;
class InnerClass{ void msg(){ System.out.println("data is "+data); } }
41
Nested Classes Example public static void main(String args[]){
TestMemberOuter1 obj=new TestMemberOuter1(); TestMemberOuter1.Inner in=obj.new Inner(); in.msg(); } }
42
Nested Classes Example abstract class Person{ abstract void eat(); }
} class TestAnonymousInner{ public static void main(String args[]){ Person p=new Person(){ void eat(){System.out.println("nice fruits"); }; p.eat(); }
43
Command Line Arguments
44
Command Line Arguments
Information that follows program's name on the command line when it is executed This data is passed to the application in the form of String arguments class Echo { public static void main (String args[]) { for (int i = 0; i < args.length; i++) System.out.printIn(args[i]); } Try this: Invoke the Echo application as follows C:\> java Echo Drink Hot Java Drink Hot Java
45
Command Line Arguments
As command line arguments are stored in String array, we have to convert this String to required primitive type by using Wrapper class's static methods. Example: Addition of two numbers class AddTwo { public static void main (String args[]) { int x = Integer.parselnt(args[0]); int y = Integer.parselnt(args[1]); int z = x + y ; System.out.println("Addition is..” + z ); } Try this: Invoke the AddTwo application as follows C:\> java AddTwo 5 7 Addition is..12
46
Static Members
47
Static Members Using static
Static keyword can be used in three scenarios: For class variables For methods For a block of code
48
Static Members Using static static variable
Static variable belongs to a class A single copy to be shared by all instances of the class Creation of instance not necessary for using static variables Accessed using <class-name>.<variable-name> unlike instance variables which are accessed as <object- name>.<variable-name> static method Static method is a class method Static method is accessed using class name.method name Creation of instance not necessary for using static methods A static method can access only other static data and methods, and not non-static members
49
Static Members Class student { private int rollNo;
private static int studcount; public Student(){ studCount++; } public void setRollNo (int r){ rollNo = r; public int getRollNo (int r){ return rollNo; public static void main{string args[]){ System.out.. println("RollNo of the Student is;” + rollNo); The static sludCounl variable is initialized to 0, ONLY when the class is first loaded, NOT each time a new instance is made Each time the constructor is invoked, i.e. an object gets created, the static variable studCount will be incremented thus keeping a count of the total no of Student objects created Which Student? Whose rollNo? A static method cannot access anything non-static Compilation Error
50
Static Members static block
A block of statement inside a Java class that is executed when a class is first loaded and initialized A class is loaded typically after the JVM starts Sometimes a class is loaded when the program requires it A static block helps to initialize the static data members like constructors help to initialize instance members class Test { static { //Code goes here }
51
Composition
52
Composition Employee Address
Composition is declaring a reference variable of a class as instance variable (member variable) in other class For example: class Address { //...} class Employee { private Address addr = new Address (); Employee Address
53
Sample Exercise Make a simple JAVA program which print “ Hello World “ thought a method named “ printMessage ” and called by object named “ obj ”. You are typing in the following program. It compiles fine, but when you execute it, you get the error java.lang.NoSuchMethodError: main. What are you doing wrong? public class Hello { public static void main() { System.out.println("Doesn't execute"); }
54
Sample Exercise What does it mean that a method has a void return type ? which method is used to read from the file ? What type of exception is divide by zero is ?
55
Solutions #1 Output: Hello World class WelcomeMessage {
printMessage() { System.out.println("Hello World"); } class Myclass { public static void main(String []args) { WelcomeMessage obj=new WelcomeMessage (); obj.printMessage(); Output: Hello World
56
Solutions #2 you forgot the String[] args. It is required.
57
Solutions #3 Its mean that this method has nothing to return.
58
Solutions #4 fileInputStraem is used to read from the file.
59
Solutions #5 This is an athematic exception .
60
Sample Exercise What will be the output of the following program
import java.util.regex.*; public class RegexExample1{ public static void main(String args[]){ Pattern p = Pattern.compile(".s");//. represents single character Matcher m = p.matcher("as"); boolean b = m.matches(); Output: True
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.