[Go to site: main page, start]

0% found this document useful (0 votes)
3 views15 pages

Java Chapter 3

The document provides an overview of Java classes and objects, explaining their fundamental properties, creation, and usage. It covers key concepts such as constructors, encapsulation, abstraction, polymorphism, and method overloading/overriding, along with examples to illustrate these concepts. Additionally, it highlights the importance of the 'this' keyword and the four main features of object-oriented programming.

Uploaded by

sujalshrestha9272
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
3 views15 pages

Java Chapter 3

The document provides an overview of Java classes and objects, explaining their fundamental properties, creation, and usage. It covers key concepts such as constructors, encapsulation, abstraction, polymorphism, and method overloading/overriding, along with examples to illustrate these concepts. Additionally, it highlights the importance of the 'this' keyword and the four main features of object-oriented programming.

Uploaded by

sujalshrestha9272
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
in nt Programmin; Fundamentals of a Class A class, in the context of Java, are templates that are used to create objects, and to define object data types and methods. Core properties include the data types and methods that may be used by the object. All class objects should have the basic class properties. Classes are categories, and objects are items within each category. A cass is a user defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type. In general, class declarations can include these components, in order: 1. Modifiers : A class can be public or has default access. 2. Class name: The name should begin with a initial letter (capitalized by convention). 3. Superclass(if any): The name of the class's parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent. 4. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface. 5. Body: The class body surrounded by braces, { }. neral form of a class is shown below: Access Modifier Class Name public class & { String breed; int age; class Volume { public static void main(String[] ergs) { Box objenew Box(); //creating instance of a class Box [Link](10,20,11.5); //calling member function using object [Link]();— //calling + + Output: Volume of a box is 2300.0 Another Example class Box{ double width FEIGHE,depth, vol; //data menbers Void getdata(double wy double h, double a) {_//nethod double calculate() { —//method volawidth*height-depth; ? return vol; class Volume { public static void main(string[] args) { Box objenew Box(); //creating instance of a class Box [Link](10,20,11.5); //calling member function using object double [Link](); — //calli [Link]("Volune of a box is “+res); Output: Volume of a box is 2300. Prepared by: Raju Poudel [MCA] 26 Passing by Reference ‘We know that in C, we can pass arguments by reference using pointers, and same can be done in C++ using references. Java is pass by value and it is not possible to pass primitives by reference in Java. Also integer class is immutable in java and java objects are references that are passed by value. So an integer object points to the exact same object as in the caller and but no changes can be made to the object which gets reflected in the caller function. Constructors Acconstructor in Java is a block of code similar to a method that’s called when an instance of ‘an object is created. Here are the key differences between a constructor and a metho + Aconstructor doesn’t have a return type. + The name of the constructor must be the same as the name of the class. + Unlike methods, constructors are not considered members of a class. + Aconstructor is called automatically when a new instance of an object is created. Alll classes have constructors, whether you define one or not, because Java automatically provides a default constructor that initializes all member variables to zero. However, once you define your own constructor, the default constructor is no longer used Following is the syntax of a constructor — class Classhane { Classtane() { a Default Constructor The defoult constructor is a constructor that is automatically generated in the absence of explicit constructors (i.e. no user defined constructor). The automatically provided constructor is called sometimes a nullary constructor. Constructor with no Arguments ‘class Box( double 1,b,h, vols + void calculate() { vol=1*bth; [Link]("Volume of a box is “4vol); public class Constructor { public static void main(String{] args) { Bok ob j=new BOX(); 0bj-caleulate(); Volume of a box is 165.0 Prepared by: Raju Poudel [MCA] a Parameterized Constructor The constructor which has parameters or arguments is known as parameterized constructor. In this type of constructor, we should supply/pass arguments while defining object of a class. The values of arguments are assigned to data members of the class. class Box{ double 1,b,h, vol; Box(double x, double y, double :){ } void calculate() { vole! [Link]("Volume of a box is "+vol); ? public class Constructor { public static void main(string[] args) { Box obj=new Box(10,5,3-3)5 obj .calculate(); r } Output: Volume of a box 1s 165.0 The this Keyword Keyword this is a reference variable in Java that refers to the current object. The various usages of 'THIS' keyword in Java are as follows: + Itcan be used to refer instance variable of current class + Itcan be used to invoke or initiate current class constructor « Itcan be passed as an argument in the method call + Itcan be passed as argument in the constructor call + Itcan be used to return the current class instance Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines this keyword. this can be used inside any method to refer to the current object. That is, this is always a reference to the object on which the method was invoked, You can use this anywhere a reference to an object of the current class’ type is permitted. // & redundant use of this. Box(double w, double h, double a) { [Link] this-height [Link] = } Prepared by: Raju Poudel [MCA] 28 //Java code for using ‘this’ keyword to //eefer current class instance variables class Test { int a5 int b; // Parameterized constructor Test(int a, int b) t this.a = a; this.b = b; } veid display() { / (Displaying value of variables a and b [Link]("a= "+a+" b=" +b); 3 public static void main(String[] args) t Test object = new Test(10, 20); object .display(); } + Output: a=10 b= 2 Prepared by: Raju Poudel [MCA] 29 Four Main Features of Object Oriented Programming: 1. Abstraction 2. Encapsulation 3. Polymorphism 4. Inheritance Abstraction Abstraction is a process of hiding the implementation details from the user, only the functionality will be provided to the user. In other words, the user will have the information ‘on what the object does instead of how it does it. In Java, abstraction is achieved using Abstract classes and interfaces. Abstract Class A class which contains the abstract keyword in its declaration is known as abstract class. + Abstract classes may or may not contain abstract methods, i.e, methods without body (public void get();) * But, if a Class has at least one abstract method, then the class must be declared abstract. + Ifa class is declared abstract, it cannot be instantiated (We cannot create object). * To use an abstract class, you have to inherit it from another dlass, provide implementations to the abstract methods in it. + If you inherit an abstract class, you have to provide implementations to all the abstract methods in it. abstract class Box{ int 1,b,h,vo! void getdata() { 1-10; bes; eas [Link]("Volume of a box is “4vol); + y public class Abstraction extends Box { public static void aain(String[] ergs) { Abstraction obj-new Abstraction(); ‘obj-getdata(); obj-caleulate(); + } Qutput: Volume of a box is 100 Prepared by: Raju Poudel [MCA] 30 Encapsulation 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, itis also known as data hiding. To achieve en: ion in Java ~ + Declare the variables of a class as private. + Provide public setter and getter methods to modify and view the variables values. Benefits of Encapsulation +The fields of a class can be made read-only or write-only. + Aclass can have total control over what is stored in its fields. class Test{ ‘ivate String name; private int age; public String getname() { return nase; + public int getage() { return ages } public void setname(string nm)/if name=nm; } public void setage(int ag) { public class Encapsulation { public static void main(String args) { Test obj=new Test(); bj. setnane(“Raaju Poudel”); obj. setage(27); [Link]("Nane: “[Link]()); [Link](“Age: “[Link]()); Name: Raaju Poudel Age: 27 Here, we cannot access private data members name and age directly. So we have created public getter and setter methods to access private data members. Prepared by: Raju Poudel [MCA] 31 Polymorphism Polymorphism in Java is a concept by which we can perform a single action in different ways. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means many forms. There are two types of polymorphism in Java: compile-time polymorphism and runtime polymorphism. We can perform polymorphism in java by method overloading and method overriding. Polymorphism in Java Runtime [Method Overloading)| (Method Overiding) Method Overloading Method Overloading Is a feature that allows a class to have more than one method having the same name, if their argument lists are different. It is similar to constructor overloading in Java, that allows a class to have more than one constructor having different argument lists. In order to overload a method, the argument lists of the methods must differ in either of these: 2) Number of parameters. ‘add(int, int) add(int, int, int) D: if Tut 4 add(int, int) add(int, float) ©) Sequence of Data type of parameters. ‘add(int, float) add{fioat, int) Prepared by: Raju Poudel [MCA] 32 Example of method overloading: class Overload { void demo (int a) t [Link] ("a: " + a); y void demo (int a, int b) { [Link] ("a and b: “+a +7," +b); t double deno(double a) { [Link]("double a: " + a); return 7a; } ? class MethodOverloading { public static void main (String args []) { Overload Obj = new Overload(); double result; Obj .demo(10); 00} .demo(e, 22)3 result = Obj .demo(5.5); [Link]("0/P : * + result); } ? Output: a: 10 a and b: 10,20 double o/P : 30.25 Here the method demo() is overloaded 3 times: first method has 4 int parameter, second method has 2 int parameters and third one is having double parameter. Which method is to be called is determined by the arguments we pass while calling methods. This happens at compile time so this type of polymorphism is known as compile time polymorphism. Prepared by: Raju Poudel [MCA] 33 Method Overriding Declaring a method in sub class which is already present in parent class is known as method ‘overriding. Overriding is done so that a child class can give its own implementation to a method which is already provided by the parent class. In this case the method in parent class is called overridden method and the method in child class is called overriding method. Let’s take a simple example to understand this. We have two classes: A child class Boy and a parent class Human. The Boy class extends Human class. Both the classes have a common method void eat (). Boy class is giving its own implementation to the eat () method or in other words it is overriding the eat () method. class Human{ //overridden method public void eat() { [Link](“Human is eating”); } class Boy extends Human{ /overriding method public void eat(){ [Link].print1n("Boy is eating"); ? public static void main( String args{]) { Boy obj = new Boy(); //This will call the child class version of eat() [Link](); } } Boy is eating Rules of method ove: gin Java 1. Argument list: The argument list of overriding method (method of child class) must match the Overridden method (the method of parent class). The data types of the arguments and their sequence should exactly match. 2. Access Modifier of the overriding method (method of subclass) cannot be more restrictive than the overridden method of parent class. For e.g. if the Access Modifier of parent class method is public then the overriding method (child class method) cannot have private, protected and default Access modifier, because all of these three access modifiers are more restrictive than public. Prepared by: Raju Poudel [MCA] 34 Another Example: Animaljava public class Aninal{ public void sound(){ [Link](“Animal is making a sound"); [Link] class Horse extends Aninal{ Goverride public void sound(){ [Link]. printIn("Neigh"); + public static void main(String args[]){ Animal obj = new Horse(); [Link]() ; Output: Neigh Recursion Java supports recursion. Recursion is the process of defining something in terms of itself. As it relates to Java programming, recursion is the attribute that allows a method to call itself. A method that calls itself is said to be recursive. The classic example of recursion is the computation of the factorial of a number. The factorial of a number N is the product of all the whole numbers between 1 and N. For example, 3 factorial is 1 x 2 x 3, or 6. Here is how a factorial can be computed by use of a recursive method: Prepared by: Raju Poudel [MCA] 35 // & simple example of recursion. class Factorial { // this is a recursive method int fact(int a) { int result; if(n==1) return 1; result = fact(n-1) * n; return result; } } class Recursion { public static void main(string args{]) { Factorial £ = new Factorial(); [Link] .printin ("Factorial of 3 is * + £.fact(3)); [Link].print1n ("Factorial of 4 is * + £.fact(4)); [Link].print1n("Factorial of 5 is * + £.fact(5)); } } The output from this program is shown here: Factorial of 3 is 6 Factorial of 4 is 24 Factorial of 5 is 120 itroducing Nested and Inner Classes It is possible to define a class within another class; such classes are known as nested classes. The scope of a nested class is bounded by the scope of its enclosing class. Thus, if class B is defined within class A, then B does not exist independently of A. A nested class has access to the members, including private members, of the class in which it is nested. However, the enclosing class does not have access to the members of the nested class. A nested class that, is declared directly within its enclosing class scope is a member of its enclosing class. It is also possible to declare a nested class that is local to a block. There are two types of nested classes: static and non-static. A static nested class is one that has the static modifier applied. Because it is static, it must access the members of its enclosing class through an object. That is, it cannot refer to members of its enclosing class directly. Because of this restriction, static nested classes are seldom used. The most important type of nested class is the inner class. An inner class is a non-static nested class. It has access to all of the variables and methods of its outer class and may refer to them directly in the same way that other non-static members of the outer class do. The following program illustrates how to define and use an inner class. The class named Outer has one instance variable named outer_x, one instance method named test( ), and defines one inner class called Inner. Prepared by: Raju Poudel [MCA] 36 // demonstrate an inner class. clase outer { int outer_x = 100; void test() { Inner inner = new Inner(); inner display (); } // this is an inner class class Inner { void display() { [Link]("display: outer_x = " + outer_x); ) } } class InnerClassDemo { public static void main(String args(1) { Outer outer = new Outer(); [Link] (); } } Output from this application is shown here: display: outer_x = 100 In the program, an inner class named Inner is defined within the scope of class Outer. Therefore, any code in class Inner can directly access the variable outer_x. An instance method named display( ) is defined inside Inner. This method displays outer_x on the standard output stream. The main( ) method of InnerClassDemo creates an instance of class Outer and invokes its test() method. That method creates an instance of class Inner and the display( ) method is called. Access Control ‘As you know, encapsulation links data with the code that manipulates it. However, encapsulation provides another important attribute: access control. Through encapsulation, you can control what parts of a program can access the members of a class. By controlling access, you can prevent misuse. For example, allowing access to data only through a well- defined set of methods, you can prevent the misuse of that data. Jave’s access specifiers are public, private, and protected. Java also defines a default access level. protected applies only when inheritance is involved. Prepared by: Raju Poudel [MCA] 37

You might also like