Classes and Objectsin Java and Inheritance in Java 1 Basics of Classes in Java Recap
2.
Contents Introduction toclasses and objects in Java. Understand how some of the OO concepts learnt so far are supported in Java. Understand important feature inheritance in Java classes. 2
3.
Introduction Java isa true OO language and therefore the underlying structure of all Java programs is classes. Anything we wish to represent in Java must be encapsulated in a class that defines the “state” and “behavior” of the basic program components known as objects. Classes create objects and objects use methods to communicate between them. They provide a convenient method for packaging a group of logically related data items and functions that work on them. A class essentially serves as a template for an object and behaves like a basic data type “int”. It is therefore important to understand how the fields and methods are defined in a class and how they are used to build a Java program that incorporates the basic OO concepts such as encapsulation, inheritance, and polymorphism. 3
4.
Classes A classis a collection of fields (data) and methods (procedure or function) that operate on that data. 4 Circle centre radius circumference() area()
5.
Classes A classis a collection of fields (data) and methods (procedure or function) that operate on that data. The basic syntax for a class definition: Bare bone class – no fields, no methods 5 public class Circle { // my circle class } class ClassName { [fields declaration] [methods declaration] }
6.
Adding Fields: ClassCircle with fields Add fields The fields (data) are also called the instance varaibles. 6 public class Circle { public double x, y; // centre coordinate public double r; // radius of the circle }
7.
Adding Methods Aclass 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: 7 type MethodName (parameter-list) { Method-body; }
8.
8 public class Circle{ public double x, y; // centre of the circle public double r; // radius of circle r = 2; //Methods to return circumference and area public double circumference() { return 2*3.14*r; } public double area() { return 3.14 * r * r; } } Method Body
9.
Data Abstraction Can definevariables (objects) of that type: Circle aCircle; Circle bCircle; Circle aCircle = new aCircle(); Circle bCircle=new bCircle(): 9 Data abstraction is the reduction of a particular body of data to a simplified representation of the whole
10.
Class of Circlecont. aCircle, bCircle simply refers to a Circle object, not an object itself. 10 aCircle Points to nothing (Null Reference) bCircle Points to nothing (Null Reference) null null
11.
11 Creating objects ofa class aCircle = new Circle(); bCircle = new Circle() ; bCircle = aCircle;
12.
Creating objects ofa class Objects are created dynamically using the new keyword. aCircle and bCircle refer to Circle objects Circle aCircle; 12 bCircle = new Circle() ; aCircle = new Circle() ;
13.
13 Creating objects ofa class aCircle = new Circle(); bCircle = new Circle() ; bCircle = aCircle; P aCircle Q bCircle Before Assignment P aCircle Q bCircle Before Assignment
14.
Automatic garbage collection The object does not have a reference and cannot be used in future. The object becomes a candidate for automatic garbage collection. Java automatically collects garbage periodically and releases the memory used to be used in the future. 14
15.
Accessing Object/Circle Data Similar to C syntax for accessing data defined in a structure. 15 Circle aCircle = new Circle(); aCircle.x = 2.0 // initialize center and radius aCircle.y = 2.0 aCircle.r = 1.0 ObjectName.VariableName ObjectName.MethodName(parameter-list)
16.
Executing Methods inObject/Circle Using Object Methods: 16 Circle aCircle = new Circle(); double area; aCircle.r = 1.0; area = aCircle.area(); sent ‘message’ to aCircle
17.
Using Circle Class //Circle.java: Contains both Circle class and its user class //Add Circle class code here class MyMain { public static void main(String args[]) { Circle aCircle; // creating reference aCircle = new Circle(); // creating object aCircle.x = 10; // assigning value to data field aCircle.y = 20; aCircle.r = 5; double area = aCircle.area(); // invoking method double circumf = aCircle.circumference(); System.out.println("Radius="+aCircle.r+" Area="+area); System.out.println("Radius="+aCircle.r+" Circumference ="+circumf); } } 17 java MyMain Radius=5.0 Area=78.5 Radius=5.0 Circumference =31.400000000000002 public class Circle { public double x, y; // centre of the circle public double r; // radius of circle //Methods to return circumference and area public double circumference() { return 2*3.14*r; } public double area() { return 3.14 * r * r; } }
18.
Inheritance in Java It is the mechanism in java by which one class is allow to inherit the features(fields and methods) of another class. class ClassName [extends SuperClassName] { [fields declaration] [methods declaration] } 18
19.
Important terminology: SuperClass: The class whose features are inherited is known as super class(or a base class or a parent class). Sub Class: The class that inherits the other class is known as sub class(or a derived class, extended class, or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods. Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class. 19
The keywordused for inheritance is extends. Syntax : class derived-class extends base-class { //methods and fields } 21
22.
Types of Inheritancein Java Single Inheritance : In single inheritance, subclasses inherit the features of one superclass. In image below, the class A serves as a base class for the derived class B. 22
23.
Example //Java program toillustrate the // concept of single inheritance import java.util.*; import java.lang.*; import java.io.*; class one { public void print_geek() { System.out.println("Geeks"); } } class two extends one { public void print_for() { System.out.println("for"); } } // Driver class public class Main { public static void main(String[] args) { two g = new two(); g.print_geek(); g.print_for(); g.print_geek(); } } 23
24.
Multilevel Inheritance InMultilevel Inheritance, a derived class will be inheriting a base class and as well as the derived class also act as the base class to other class. In below image, the class A serves as a base class for the derived class B, which in turn serves as a base class for the derived class C. In Java, a class cannot directly access the grandparent’s members. 24
Example for multilevelInheritance import java.util.*; import java.lang.*; import java.io.*; class one { public void print_geek() { System.out.println("Geeks"); } } class two extends one { public void print_for() { System.out.println("for"); } } class three extends two { public void print_geek() { System.out.println("Geeks"); } } // Drived class public class Main { public static void main(String[] args) { three g = new three(); g.print_geek(); g.print_for(); g.print_geek(); } } 26
27.
Hierarchical Inheritance : In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one sub class.In below image, the class A serves as a base class for the derived class B,C and D. 27
28.
// Java programto illustrate the // concept of Hierarchical inheritance import java.util.*; import java.lang.*; import java.io.*; class one { public void print_geek() { System.out.println("Geeks"); } } class two extends one { public void print_for() { System.out.println("for"); } } class three extends one { /*............*/ } // Drived class public class Main { public static void main(String[] args) { three g = new three(); g.print_geek(); two t = new two(); t.print_for(); g.print_geek(); } } 28
29.
Multiple Inheritance (Through Interfaces) In Multiple inheritance ,one class can have more than one superclass and inherit features from all parent classes. Please note that Java does not support multiple inheritance with classes. In java, we can achieve multiple inheritance only through Interfaces. In image below, Class C is derived from interface A and B. 29
Example of MultipleInheritance // Java program to illustrate the // concept of Multiple inheritance import java.util.*; import java.lang.*; import java.io.*; interface one { public void print_geek(); } interface two { public void print_for(); } interface three extends one,two { public void print_geek(); } class child implements three { @Override public void print_geek() { System.out.println("Geeks"); } public void print_for() { System.out.println("for"); } } // Drived class public class Main { public static void main(String[] args) { child c = new child(); c.print_geek(); c.print_for(); c.print_geek(); } } 31
32.
Hybrid Inheritance(Through Interfaces) Itis a mix of two or more of the above types of inheritance. Since java doesn’t support multiple inheritance with classes, the hybrid inheritance is also not possible with classes. In java, we can achieve hybrid inheritance only through Interfaces. 32
Advantages of Inheritance Reusability -- facility to use public methods of base class without rewriting the same Extensibility -- extending the base class logic as per business logic of the derived class Data hiding -- base class can decide to keep some data private so that it cannot be altered by the derived class Overriding -- With inheritance, we will be able to override the methods of the base class so that meaningful implementation of the base class method can be designed in the derived class. 34
35.
Method Overloading Ifa class has multiple methods having same name but different in parameters, it is known as Method Overloading. It is also known as Compile-Time Polymorphism 35
36.
Overloading If wehave to perform only one operation, having same name of the methods increases the readability of the program 36
37.
Overloading Different waysto overload the method There are two ways to overload the method in java By changing number of arguments By changing the data type 37
38.
Overloading 1) MethodOverloading: changing no. 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 TestOverloading1{ public static void main(String[] args){ System.out.println(Adder.add(11,11)); System.out.println(Adder.add(11,11,11)); }} 38
39.
Overloading 2) MethodOverloading: changing data type of arguments class Adder{ int add(int a, int b){return a+b;} double add(double a, double b){return a+b;} } class TestOverloading2{ public static void main(String[] args){ Adder ob1= new Adder(); Ob1.add(11,11); Ob1.add(11,12.6); //System.out.println(Adder.add(11,11)); //System.out.println(Adder.add(12.3,12.6)); }} 39
40.
Method Overriding Ifsubclass (child class) has the same method as declared in the parent class, it is known as method overriding in Java. In other words, If a subclass provides the specific implementation of the method that has been declared by one of its parent class, it is known as method overriding. 40
41.
Overriding Overriding isa feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. 41
42.
Overriding When amethod in a subclass has the same name, same parameters or signature, and same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class. 42
Usage of JavaMethod Overriding Method overriding is used to provide the specific implementation of a method which is already provided by its superclass. Method overriding is used for runtime polymorphism 44
45.
Rules forJava Method Overriding The method must have the same name as in the parent class The method must have the same parameter as in the parent class. There must be an IS-A relationship (inheritance). 45
46.
Overriding class Vehicle{ //defining amethod void run(){System.out.println("Vehicle is running");} } //Creating a child class class Bike2 extends Vehicle{ //defining the same method as in the parent class void run(){System.out.println("Bike is running safely");} public static void main(String args[]){ Bike2 obj = new Bike2();//creating object obj.run();//calling method } } Output: Bike is running safely 46
47.
Scope of theVariable Method Scope Variables declared directly inside a method are available anywhere in the method following the line of code in which they were declared. 47
48.
Scope of Variablesin Java Scope is that area of the program where the variable is visible to a program and can be used (accessible). i.e. the scope of variable determines its accessibility for other parts of program. Java allows declaring variables within any block. A block defines scope that starts with an opening curly brace and ends with a closing curly brace. There are three types of variables in java, depending on their scope: local variables, instance variables, and class variables (static variables). 48
49.
Scope of Variablesin Java 1. Scope of Local Variables in Java 2. Scope of Instance variables in Java 3. Scope of Static variables 49
50.
Scope of themethod public class MyClass { public static void main(String[] args) { // Code here cannot use x int x = 100; // Code here can use x System.out.println(x); } } 50
51.
Block Scope Ablock of code refers to all of the code between curly braces {} Variables declared inside blocks of code are only accessible by the code between the curly braces which follows the line in which the variable was declared. A block of code may exist on its own or it may belong to an if, while or for statement. In the case of for statements, variables declared in the statement itself are also available inside the block's scope. 51
52.
Example Program public classMyClass { public static void main(String[] args) { // Code here CANNOT use x { // This is a block // Code here CANNOT use x int x = 100; // Code here CAN use x System.out.println(x); } // The block ends here // Code here CANNOT use x } } 52
53.
Java Modifiers Modifiers dividedinto two groups: Access Modifiers - controls the access level Non-Access Modifiers - do not control access level, but provides other functionality 53
54.
The four primaryaccess modifiers in Java are: Default access modifier Protected access modifier Public access modifier Private access modifier 54
55.
Access Modifiers For classes,we can use either public or default public :The class is accessible by any other class default :The class is only accessible by classes in the same package. This is used when you don't specify a modifier. //You will learn more about packages in the Packages chapter 55
56.
Access Modifiers For attributes,methods and constructors, you can use one of the following: public :The code is accessible for all classes private :The code is only accessible within the declared class default :The code is only accessible in the same package. This is used when you don't specify a modifier. You will learn more about packages in the Packages chapter protected :The code is accessible in the same package and subclasses. You will learn more about subclasses and superclasses in the Inheritance chapter 56
57.
Non-Access Modifiers For classes,we can use either final or abstract: final:The class cannot be inherited by other classes abstract :The class cannot be used to create objects (To access an abstract class, it must be inherited from another class. You will learn more about inheritance and abstraction in the Inheritance and Abstraction chapters) 57
58.
Non Access Modifiers finalAttributes and methods cannot be overridden/modified static Attributes and methods belongs to the class, rather than an object abstract Can only be used in an abstract class, and can only be used on methods. The method does not have a body, for example abstract void run();. The body is provided by the subclass (inherited from). You will learn more about inheritance and abstraction in the Inheritance and Abstraction chapters transient Attributes and methods are skipped when serializing the object containing them synchronize d Methods can only be accessed by one thread at a time volatile The value of an attribute is not cached thread-locally, and is always read from the "main memory" 58
Java Package Ajava package is a group of similar types of classes, interfaces and sub-packages. Package in java can be categorized in two form, built-in package and user-defined package. 61
62.
Java Packages Thereare many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc. Advantage of Java Package Java package is used to categorize the classes and interfaces so that they can be easily maintained. Java package provides access protection. Java package removes naming collision. 62
Default access modifiers The default access modifier is accessible to any package by default. The programmers need not specify any keyword to use the default access modifier. It means that the programmer doesn’t need to specify a class, method, or constructor default explicitly. A class or method is, by default, accessible from any other “class” that exists in the same package. We usually don’t define variables and methods with any access modifier. 70
70.
Example Code class Def{ int num = 175; void print() { System.out.println("Default class " + num); } } public class Test { public static void main(String args[]) { Def def = new Def(); def.print(); } } Output: Default class 175 71
71.
Private access modifiers As the name suggests, the private access modifier limits access to the defining “class” only. With the help of the “private” keyword, we can implement the real concept of Data Encapsulation. It means to hide the private members form the outside world. The functions labeled as private are accessible within the class only. You can’t declare a top-level class or interface as private. Also, if so, then it would be useless as no one could access it. The programmer must define a getter or setter to access private methods or variables. 72
72.
The example belowwill help you visualize a getter for the private method: class Priv { private void PRINT() { System.out.println("Private access"); } public void getPrint() { PRINT(); } } public class Test { public static void main(String args[]) { Private priv = new Priv(); priv.PRINT(); } } Output:Private access 73
73.
Public access modifiers The public modifiers are the most common in Java applications. They mean that any public class, method, variable, interface, or constructor is accessible throughout the package. Before using a public class in another package, you must first import it. If you inherit a public class, then the subclass will have all its methods and variables by default. 74
74.
Example Code ForPublic access modifier public class First { public void print() { System.out.println("Hello"); } public class Test extends First { public static void main(String args[]) { First first = new First(); first.print(); } } Output:Hello 75
75.
Protected access modifiers Objects or methods having protected access are visible to the package and subclasses only. The following are a few points to elaborate on the exact behavior: These methods, variables, or constructors are accessible within the package only and also available to all the subclasses. The protected keyword doesn’t apply to any class or interface. Interface methods or variables can’t have protected access. 76
76.
Example Code forProtected Access: public class First { protected static int count; public void update(){ System.out.println(++count); } public class Test extends First { public static void main(String args[]) { First out = new First(); out.update(); } } }Output:1 77
77.
Non-access modifiers Static– It means something is directly related to a class. Final – It indicates that the object is immutable. Abstract – It means you need to subclass for creating objects. Synchronized – It indicates that only one thread can execute a method at a time. Transient – It means to exclude something during serialization. Volatile – It indicates that different threads can modify a variable’s value. Native – It shows that the method is available in the native code using JNI or JNA. 78
78.
Static Modifier StaticModifier is used for creating a static variable and static method. The reserved keyword for a static modifier is static, which is used before the data type of the variable or method. A static method or variable exists independently of any class object. It means a static variable or static method can be called using the class name without creating an instance or object of this class. 79
79.
Static Modifier Car.java publicclass Car{ public static String msg; //String type static variable is declared public static void create(){ System.out.print(msg); //Variable msg is passed as argument to print. } } 80
80.
Static Modifier Main.java public classMain { //initialization of class public static void main(String[] args) { //value is stored in static variable Car.msg = "A new car has been created"; // static method in class Car is invoked Car.create(); } } 81
81.
Final Modifier InJava, variable, method, and class can have a final non-access modifier. The reserved keyword for a final non-access modifier is final. This keyword is used to make any class, method, or variable final. Once a final variable is initialized, you cannot change its value again. A final variable that is uninitialized is called a blankfinal variable that can be initialized only in the constructor of a class. To make a class variable, sometimes, we use the static keyword with final. If a static final variable is not initialized, we can initialize it in a static block. 82
82.
Final Modifier public classMain{ //initialization of class //declare a final variable of int data type public final int number = 1; //non-static method to print number value public void print(){ System.out.print(number); //print number number = 2; //change value of number System.out.print(number); //print new value } // main method public static void main(String[] args){ //object of class Main to access non-static methods Main p = new Main(); //print method invoked p.print(); } } //end of class 83
83.
If we removecode at line 11, the modified code would be executed without any error. Code Example for Final Variable: public class Main{ //initialization of class //declare a final variable of int data type public final int number = 1; //non-static method to print number value public void print(){ System.out.print("Output is "+number); //print number } // main method public static void main(String[] args){ //object of class Main to access non-static methods Main p = new Main(); //print method invoked p.print(); } } //end of class 84
84.
Code Examplefor Static Final Variable: public class Main{ //initialization of class //declare a static final variable of int data type public static final int number = 1; // main method public static void main(String[] args){ System.out.print("Output is "+number); //print number } } //end of class A method that we cannot override is called final method. It can be inherited in any other class. 85
85.
Code Example forFinal Method: Car.java public class Car{ //final method public final void create(){ System.out.print("I'm final method to create a car."); } } Main.java //initialization of class public class Main extends Car{ //non-static method to access non-static methods in Car.java public void makeCar(){ create(); //method invoked } // main method public static void main(String[] args){ Main m = new Main(); //object of Main class m.makeCar(); //call to makeCar method } //end of main method } //end of class 86
86.
A class thatwe cannot extend is called final class. It means a final class cannot be inherited by any other class. Code Example for Final Class: Car.java public final class Car{ //void method public void print(){ //method body } } Main.java //initialization of class public class Main extends Car{ public static void main(String[] args){ } //end of main method } //end of class 87
87.
Abstract Modifier Aclass or method can be declared as abstract. Reserved keyword abstract is used for the abstract modifier. An abstract class or method cannot be final because an abstract class is made with the purpose of extending it in other classes and an abstract method is made for the sole purpose of overriding the method body. To make a class abstract, at least one abstract method should be defined in a class. If we have to declare abstract methods in a class, a class must be an abstract class. An abstract method is just a declaration; it does not contain an implementation or method body. You will have to define its implementation by overriding this method in a class, which has extended the abstract class. When a class extends an abstract class, all the abstract methods defined in the abstract class must be overridden in a subclass. 88
88.
Example Code: AbstactModifier Car.java public abstract class Car{ public abstract void create(); public void print(){ System.out.print("I'm not abstract method."); } } 89 Main.java //initialization of class public class Main extends Car{ // overriding method defined in Car class //as create is only abstract method in Car class //overriding it is compulsory //otherwise error will occur @Override public void create(){ System.out.println("I'm overridden method."); } // main method public static void main(String[] args){ Main m = new Main(); //object of Main class m.create(); //invoking overridden method m.print(); } //end of main method } //end of class
89.
Volatile Modifier Thismodifier is applied only to private or object type instance field or variable. Reserved keyword for this modifier is volatile. It indicates to the JVM to merge a thread’s own copy of field with the master copy of field available in memory. When we access a volatile variable, it synchronizes all the available cached copies of variables in memory. 90
90.
Volatile Modifier public classSalary implements Runnable { private volatile int salary; public void run() { salary = 5000; //assigning value to salary do{ //loop body } while (salary <= 5000); // while loop definition } public void stop() { salary = 5001; // new value assignment to salary } } 91
91.
Transient Modifier Whenwe use a transient modifier in an instance variable declaration, the JVM will skip this variable or field while serializing the object containing that variable. Reserved keyword is transient. 92
Synchronized Modifier Amodifier that is used to restrict a method to be used by any other thread when it is under use of one thread. Reserved keyword for this modifier is synchronized. The synchronized modifier can be used with any access modifier. 94
Abstract Classes andMethods Data abstraction is the process of hiding certain details and showing only essential information to the user. Abstraction can be achieved with either abstract classes or interfaces (which you will learn more about in the next chapter). 96
96.
Abstract Classes andMethods The abstract keyword is a non-access modifier, used for classes and methods: Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class). Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the subclass (inherited from). 97
97.
Abstract Classes Anabstract class can have both abstract and regular methods: abstract class Animal { public abstract void animalSound(); public void sleep() { System.out.println("Zzz"); } } 98
98.
Abstract Classes Fromthe example above, it is not possible to create an object of the Animal class: Animal myObj = new Animal(); // will generate an error To access the abstract class, it must be inherited from another class 99
99.
Abstract Classes // Abstractclass abstract class Animal { // Abstract method (does not have a body) public abstract void animalSound(); // Regular method public void sleep() { System.out.println("Zzz"); } } // Subclass (inherit from Animal) class Pig extends Animal { public void animalSound() { // The body of animalSound() is provided here System.out.println("The pig says: wee wee"); } } 100 class MyMainClass { public static void main(String[] args) { Pig myPig = new Pig(); // Create a Pig object myPig.animalSound(); myPig.sleep(); } }
100.
JAVA Packages Ajava package is a group of similar types of classes, interfaces and sub-packages. Package in java can be categorized in two form, built-in package and user-defined package. 101
101.
JAVA Packages Advantage ofJava Package 1) Java package is used to categorize the classes and interfaces so that they can be easily maintained. 2) Java package provides access protection. 3) Java package removes naming collision. 102
Java Packages Categories Built-in Packages (packages from the Java API) User-defined Packages (create your own packages) 104
104.
Built-in Packages TheJava API is a library of prewritten classes, that are free to use, included in the Java D To use a class or a package from the library, you need to use the import keyword:evelopment Environment. Syntax import package.name.Class; // Import a single class import package.name.*; // Import the whole package 105
105.
Built-in Packages Ifyou find a class you want to use, for example, the Scanner class, which is used to get user input, write the following code: Example import java.util.Scanner; 106
106.
Example import java.util.Scanner; class MyClass {public static void main(String[] args) { Scanner myObj = new Scanner(System.in); System.out.println("Enter username"); String userName = myObj.nextLine(); System.out.println("Username is: " + userName); } } 107
107.
Import a Package To import a whole package, end the sentence with an asterisk sign (*). The following example will import ALL the classes in the java.util package: Example import java.util.*; 108
108.
User-defined Packages Tocreate your own package, you need to understand that Java uses a file system directory to store them. Just like folders on your computer: Example └── root └── mypack └── MyPackageClass.java 109
109.
MyPackageClass.java To createa package, use the package keyword: package mypack; class MyPackageClass { public static void main(String[] args) { System.out.println("This is my package!"); } } 110
110.
Java Packages Savethe file as MyPackageClass.java, and compile it: C:UsersYour Name>javac MyPackageClass.java compile the package: C:UsersYour Name>javac -d . MyPackageClass.java 111
111.
Java Packages To runthe MyPackageClass.java file, write the following: C:UsersYour Name>java mypack.MyPackageClass The output will be: This is my package! 112
112.
Java Packages Simpleexample of java package //save as Simple.java package mypack; public class Simple{ public static void main(String args[]){ System.out.println("Welcome to package"); } } 113