Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
30 views

2016-20module 4 Java

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

2016-20module 4 Java

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 66

MODULE 4

Programming with JAVA – Overview of


Java Language, Classes Objects and
Methods, Method Overloading and
Inheritance, Overriding Methods, Final
Variables and Methods. Interfaces,
Packages, Multithreaded programming,
Managing Errors and Exceptions.
 Java programming language was originally developed by Sun
Microsystems which was initiated by James Gosling and released in
1995 as core component of Sun Microsystems' Java platform (Java
1.0 [J2SE]).
 The latest release of the Java Standard Edition is Java SE 8. With the
advancement of Java and its widespread popularity, multiple
configurations were built to suit various types of platforms. For
example: J2EE for Enterprise Applications, J2ME for Mobile
Applications.
 The new J2 versions were renamed as Java SE, Java EE, and Java
ME respectively. Java is guaranteed to be Write Once, Run
Anywhere.
 Java is used to develop two types of applications
 Standalone applications
 Web Applets (for internet applications)

Execution of Standalone applications involves


Two steps
1) Compiling the source code into byte code using
javac compiler
2) Executing byte code using java interpreter
 Java is −
 Object Oriented − In Java, everything is an Object. Java can be easily
extended since it is based on the Object model.
 Platform Independent − Unlike many other programming languages including
C and C++, when Java is compiled, it is not compiled into platform specific
machine, rather into platform independent byte code. This byte code is
distributed over the web and interpreted by the Virtual Machine (JVM) on
whichever platform it is being run on.
 Simple − Java is designed to be easy to learn. If you understand the basic
concept of OOP Java, it would be easy to master.
 Secure − With Java's secure feature it enables to develop virus-free, tamper-
free systems. Authentication techniques are based on public-key encryption.
 Architecture-neutral − Java compiler generates an architecture-neutral object
file format, which makes the compiled code executable on many processors,
with the presence of Java runtime system.
 Portable − Being architecture-neutral and having no implementation dependent
aspects of the specification makes Java portable.
 Java is −
 Robust − Java makes an effort to eliminate error prone situations by
emphasizing mainly on compile time error checking and runtime checking.
Compile-time is the instance where the code you entered is converted to executable while Run-time is
the instance where the executable is running.
 Multithreaded − With Java's multithreaded feature it is possible to write
programs that can perform many tasks simultaneously. This design feature
allows the developers to construct interactive applications that can run
smoothly.
 Interpreted − Java byte code is translated on the fly to native machine
instructions and is not stored anywhere. The development process is more rapid
and analytical since the linking is an incremental and light-weight process.
 Dynamic − Java is considered to be more dynamic than C or C++ since it is
designed to adapt to an evolving environment. Java programs can carry
extensive amount of run-time information that can be used to verify and resolve
accesses to objects on run-time.
 When we consider a Java program, it can be defined as a collection of objects
that communicate via invoking each other's methods.

 Object − Objects have states and behaviors. Example: A dog has states -
color, name, breed as well as behavior such as wagging their tail, barking,
eating. An object is an instance of a class.
 Class − A class can be defined as a template/blueprint that describes the
behavior/state that the object of its type supports.
 Methods − A method is basically a behavior. A class can contain many
methods. It is in methods where the logics are written, data is manipulated
and all the actions are executed.
 Instance Variables − Each object has its unique set of instance variables. An
object's state is created by the values assigned to these instance variables.
public class MyFirstJavaProgram
{ /* This is my first java program.
* This will print 'Hello World' as the output */
public static void main(String []args) {
System.out.println("Hello World"); // prints
Hello World
}
}
Class SampleOne
{ public static void main(String args[])
{ System.out.println(“Java is better than C++”);
}
}
# Class concepts are similar to one learned earlier
as an integral part of OOP. Class is a keyword
and SampleOne is a Java Identifier
Class SampleOne
{ public static void main(String args[])
{ System.out.println(“Java is better than C++”);
}
}
# main is a method. Every Java program should have a main.
This is the starting point of execution of the program to the
interpreter. A Java program can have many classes but only
one of the classes can contain the main function. Java
Applets do not use main method.
Class SampleOne
{ public static void main(String args[])
{ System.out.println(“Java is better than C++”);
}
}
# public: access specifier for the main function, making it unprotected and
accessible for all other classes.
# Static: declare the method to belong to the class and not to the objects. main is
declared as static for usage before objects are created.
# void – the return type and nothing is returned.
# parameters to the method “main” is declared as strings called args which can be
an array also.
# println: appends newline character to the end of the string
-
class Room { float area;
{ float length; Room room1 = new Room();
float breadth;
void getdata(float a, float b) room1.getdata(14,10);
{ length = a; area = room1.length*
breadth = b; room1.breadth;
} System.out.println("Area =
} "+area);
class RoomArea }
{ public static void main(String }
args[])
class Main {
public static void main (String[] args)
{ float a = 2;
float b = 4;
System.out.println(" Before Swapping: a" + a);
System.out.println(" Before Swapping: b" + b);
float c =a;
a = b;
b = c;
System.out.println(" After Swapping: a " + a);
System.out.println(" After Swapping: b " + b);
}
};
class calculate_accept System.out.println("The difference of given
{ int a,b; numbers = "+d);
void accept_no(int p, int q) System.out.println("The product of given
{ a=p; numbers = "+e);
b=q; System.out.println("The quotient of given
numbers = "+f);
System.out.println("The first number is "+a);
}
System.out.println("The second number is
"+b); };
} class Main{
void calculate_result() public static void main (String[] args)
{ int c = a+b; { calculate_accept obj1 = new
calculate_accept();
int d = a-b;
obj1.accept_no(10,2);
int e = a*b;
obj1.calculate_result();
int f = a/b;
}
System.out.println("The sum of given numbers =
"+c); }
import java.util.Scanner;
class PrimeNumberDemo
{ public static void main(String args[]) for ( int i = 2 ; i <=n ; )
{ int n; { for ( int j = 2 ; j <= Math.sqrt(num) ; j++ )
int status = 1; { if ( num%j == 0 )
int num = 3; { status = 0;
//For capturing the value of n break;
Scanner scanner = new Scanner(System.in); }
System.out.println("Enter the value of n:"); }
//The entered value is stored in the var n if ( status != 0 )
n = scanner.nextInt(); { System.out.println(num);
if (n >= 1) i++;
{ System.out.println("First "+n+" prime }
numbers are:"); status = 1;
//2 is a known prime number num++;
System.out.println(2); }
} }
}
PROGRAM TO READ A VALUE AND CALCULATE

import java.util.Scanner; r = s.nextInt();


class Main area = pi * r * r;
{ System.out.println("Area of
public static void main(String[] circle:"+area);
args) }
{ }
int r;
double pi = 3.14, area; System.in is referiing to the fact
Scanner s = new that the input will be passed by the
Scanner(System.in); console i.e. keyboard
System.out.println("Enter nextInt(); will be reading the value
radius of circle:"); into r
GENERAL STRUCTURE OF A JAVA PROGRAM
 Documentation: comprises the set of comment lines giving name
of the author, explaining “how” and “why” of the program.
 1/* text */

The compiler ignores everything from /* to */.


 2//text

The compiler ignores everything from // to the end of the line.


 3/** documentation */

This is a documentation comment and in general its called doc


comment. The JDK javadoc tool uses doc comments when
preparing automatically generated documentation.
 A java 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.


 There are many built-in packages such as java, lang, awt, javax,

swing, net, io, util, sql etc.


 Advantage of Java 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.
BUILT IN CLASSES AND PACKAGES
java.lang Provides classes that are fundamental
to the design of the Java programming language
such as String, Math, and basic runtime support
for threads and processes.
java.util Provides the collections framework,
formatted printing and scanning, array
manipulation utilities, event model, date and time
facilities, internationalization, and miscellaneous
utility classes.
Java AWT (Abstract Window Toolkit) is an API
to develop GUI or window-based applications in
java.
Java AWT components are platform-dependent
i.e. components are displayed according to the
view of operating system. AWT is heavyweight
i.e. its components are using the resources of OS.
The java.awt package provides classes for AWT
api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
 Packages and Interfaces both acts as a container. The content
in packages and interfaces can be used by the classes by
importing and implementing it correspondingly. The basic
difference between packages and interfaces is that a package
contains a group of classes and interfaces whereas, an
interface contains methods and fields.
 The difference between Package and Interface in Java is that
Package helps to categorize the classes methodically to
access and maintain them easily while Interface helps to
implement multiple inheritances and to achieve abstraction.
BASIS FOR
PACKAGES INTERFACES
COMPARISON
Basic Packages is a group of classes and/or Interfaces is a group of
interfaces together. abstract methods and
constant fields.
Keyword Packages are created using "Package" Interface are created using
keyword. "Interface" keyword.
Syntax package package_name; interface interface_name{
public class class_name{ variable declaration;
. method declaration;
(body of class) }
.
}
Access A package can be imported An interface can be extended
by another interface and
implemented by the class.
Access keyword Packages can be imported using Interfaces can be
"import" keyword. implemented using
"implement" keyword.
 Import statement performs the same //save by A.java
functions as the #include statements. package pack;
 This is used to load a class from a public class A {
package. public void msg()
 if you { System.out.println("Hello");
import packagename.classname then } }
only the class with
//save by B.java
name classname in the package with
name packagename will be available package mypack;
for use. import pack.A;
class B {
public static void main(String args[]) {
A obj = new A(); obj.msg(); } }
 Example :
 Interface is a kind of a class, but, differs in a sense that the methods declared in
the interface are abstract that means the methods are only declared but not
defined. The fields in the interface are always public, static, final. The fields must
be initialized at the time of declaration. The methods declared by the interface are
defined by the class which implements that interface according to its requirement.
As the methods in the interface do not perform any function, so there is no use of
creating any object of the interface. Hence, no object can be created for the
interface.

 The interface can also inherit the other interface but, the class inheriting such an
interface must also implement all the methods of the inherited interface. As the
fields are initialized at the time of their declaration in the interface, so there is no
need of constructor in the interface hence, the interface doesn’t contain any
constructor. Let’s see the example of creating and using an interface.
interface Area };
{
double pi= 3.14; class Main
double find_area(double a,double b); {
} public static void main(String args[ ])
{
class Circle implements Area Circle C= new Circle ( );
{ double F= C.find_area(10,10);
public double find_area(double a, System.out.println("Area of the
double b) circle is : " + F);
{ }
return (pi*a*b); }
}
Both packages and interface are the
containers. Package reduces the size of the
code as we just import the class to be used
instead of again define it.

Whereas the interface reduces the confusions


occurred while multiple inheritances because
in the case of multiple inheritances the
inheriting class has not to decide that
definition of which method it should inherit
instead it defines its own.
`
 Class definitions: Classes are primary elements of
a OOP. The number of classes can vary with the
complexity of the program.
 Main Method Class: The class that contains the
main program. The only part that is essential to
ensure the start and termination of the
functioning of the program.
CLASS, OBJECT AND METHOD
 Object − Objects have states and behaviors.
Example: A dog has states - color, name, breed as
well as behaviors – wagging the tail, barking,
eating. An object is an instance of a class.
 Class − A class can be defined as a
template/blueprint that describes the
behavior/state that the object of its type support.
CLASS, OBJECT AND METHOD
 Defining a class
Class classname [extends superclassname]
{
{ fields declaration;
methods declaration;
}
}
Extends is a keyword indicating the properties of the
superclassname class is extended/inherited to the classname
class.
CLASS, OBJECT AND METHOD
 Local Variables
 Local variables are declared in methods,  Example
constructors, or blocks.  Here, age is a local variable. This is defined
 Local variables are created when the method, inside pupAge() method and its scope is limited
constructor or block is entered and the variable to only this method.
will be destroyed once it exits the method, public class Test {
constructor, or block. public void pupAge() {
 Access modifiers cannot be used for local int age = 0;
variables.
age = age + 7;
 Local variables are visible only within the
System.out.println("Puppy age is : " + age);
declared method, constructor, or block.
}
 Local variables are implemented at stack level
internally.
 There is no default value for local variables, so public static void main(String args[]) {
local variables should be declared and an initial Test test = new Test();
value should be assigned before the first use. test.pupAge();
}
}
VARIABLES
 What is a Local Variable?
 A local variable in Java is typically used in a method, constructor, or bloc and
has only local scope. So, you can use the variable only within the scope of a
block. Other methods in the class aren't even aware that the variable exists.

 Example

 if(x > 100) {


 String testLocal = "some value";
 }

 In the above case, you cannot use testLocal outside of that if block.
VARIABLES
 What is an Instance Variable? 

 An instance variable is a variable that's bound to  class TestClass{


the object itself. Instance variables are declared  public String StudentName;
in a class , but outside a method. And every  public int age;
instance of that class (object) has it's own copy 
}
of that variable. Changes made to the variable
don't reflect in other instances of that class.
Instance variables are available to any method  Rules for Instance variable
bound to an object instance . As a practical  Instance variables can use any of the four access
matter, this generally gives it scope within some levels
instantiated class object. When an object is  They can be marked final
allocated in the heap , there is a slot in it for each  They can be marked transient
instance variable value. Therefore an instance 
They cannot be marked abstract
variable is created when an object is created and
destroyed when the object is destroyed.
 They cannot be marked synchronized
 They cannot be marked native
 Example
 They cannot be marked static
VARIABLES
 What is a Class Variable  Example
 Class variables are declared with 
keyword static , but outside a  public class Product {
method. So, they are also known  public static int Barcode;
as static member variables and 
}
there's only one copy of that
variable is shared with all
instances of that class. If changes  Class Variables are stored in
are made to that variable, all static memory . It is rare to use
other instances will see the effect static variables other than
of the changes. declared final and used as either
public or private constants.
CLASS, OBJECT AND METHOD
 Instance variables are declared in a class, but Normally, it is recommended to make these
outside a method, constructor or any block. variables private (access level). However,
 When a space is allocated for an object in the visibility for subclasses can be given for these
heap, a slot for each instance variable value is variables with the use of access modifiers.
created.  Instance variables have default values. For
 Instance variables are created when an object is numbers, the default value is 0, for Booleans it
created with the use of the keyword 'new' and is false, and for object references it is null.
destroyed when the object is destroyed. Values can be assigned during the declaration
 Instance variables hold values that must be or within the constructor.
referenced by more than one method,  Instance variables can be accessed directly by
constructor or block, or essential parts of an calling the variable name inside the class.
object's state that must be present throughout However, within static methods (when instance
the class. variables are given accessibility), they should
 Instance variables can be declared in class level be called using the fully qualified
before or after use. name. ObjectReference.VariableName.
 Access modifiers can be given for instance
variables.
 The instance variables are visible for all
methods, constructors and block in the class.
CLASS, OBJECT AND METHOD
import java.io.*; public void setSalary(double empSal) {
public class Employee { salary = empSal;
}
// this instance variable is visible for any child
class. // This method prints the employee details.
public String name; public void printEmp() {
System.out.println("name : " + name );
// salary variable is visible in Employee class System.out.println("salary :" + salary);
only. }
private double salary;
public static void main(String args[]) {
// The name variable is assigned in the Employee empOne = new
constructor. Employee("Ransika");
public Employee (String empName) { empOne.setSalary(1000);
name = empName; empOne.printEmp();
} }
}
// The salary variable is assigned a value.
CLASS, OBJECT AND METHOD
 Class variables also known as static variables public since they must be available for users of
are declared with the static keyword in a class, the class.
but outside a method, constructor or a block.  Default values are same as instance variables.
 There would only be one copy of each class For numbers, the default value is 0; for
variable per class, regardless of how many Booleans, it is false; and for object references,
objects are created from it. it is null. Values can be assigned during the
 Static variables are rarely used other than being declaration or within the constructor.
declared as constants. Constants are variables Additionally, values can be assigned in special
that are declared as public/private, final, and static initializer blocks.
static. Constant variables never change from  Static variables can be accessed by calling with
their initial value. the class name ClassName.VariableName.
 Static variables are stored in the static memory.  When declaring class variables as public static
It is rare to use static variables other than final, then variable names (constants) are all in
declared final and used as either public or upper case. If the static variables are not public
private constants. and final, the naming syntax is the same as
 Static variables are created when the program instance and local variables.
starts and destroyed when the program stops.
 Visibility is similar to instance variables.
However, most static variables are declared
CLASS, OBJECT AND METHOD
import java.io.*;
public class Employee2 {

// salary variable is a private static variable


private static double salary;

// DEPARTMENT is a constant
public static final String DEPARTMENT =
"Development ";

public static void main(String args[]) {


salary = 1000;
System.out.println(DEPARTMENT + "average
salary:" + salary);
}
}
CLASS, OBJECT AND METHOD
Field Declaration return (area); }
Class Rectangle
{ int length, width; Creating Objects
} Rectangle rect1; //declare the object
Class Rectangle rect1 = new Rectangle(); //instantiate the
{ int length; int width; object OR
Rectangle rect1 = new Rectangle();
}
Method Declaration
type methodname(parameter-list)
Accessing Class Members
objectname.variablename = value;
{ Method-body;
Objectname.methodname(parameter-list)
}
Ex: rect1.length = 15;
Ex: void getData(int x ,int y)
Rect1.getdata(20,15)
{ length = x; width = y;}
area1=rect1.rectArea()
int rectArea()
{ int area = length*width;
CLASS, OBJECT AND METHOD
class Rectangle Rectangle rect1 = new Rectangle();
{int length, width; rect1.getData(15,10);
void getData (int x, int y) area1=rect1.length*rect1.width;
{length = x ; width = y;}; Rectangle rect2 = new Rectangle();
int rectArea() rect2.length = 20;
{ int area = length*width; rect2.width = 20;
return area; area2=rect2.rectArea();
} System.out.println("The Area of rect1
} =" + area1);
System.out.println("The Area of rect2
class rectArea =" + area2);
{ }
public static void main(String args[]) }
{int area1,area2;
CLASS, OBJECT AND METHOD
CONSTRUCTORS

class perimeter
Parameterized Constructor { int length, breadth;
Rectangle (int x, int y) perimeter()
{length =0; breadth = 0;}
{ length =x; width = y;} perimeter(int x, int y)
{length =x; breadth = y;}
void perimeter_calc()

Default Constructor { int perimeter = 2*(length+breadth);


System.out.println("The perimeter =" + perimeter);
Perimeter() }
}
{length = 0; width = 0;} class main_perimeter
{public static void main(String args[])
{ perimeter p1 = new perimeter();
perimeter p2 = new perimeter(2,5);
p1.perimeter_calc();
p2.perimeter_calc();
}}
CLASS, OBJECT AND METHOD
breadth = y;
Method Overloading
}
Room(float x)
Methods have the same name but { length = breadth = x;
different parameter list and different }
definitions. float area()
{ area = length*breadth;
Used when objects are required to
return area;
perform similar tasks but using }}
different input parameters. class Room_main
Ex of polymorphism { public static void main (String args[])
{ Room obj1 = new Room(5);
System.out.println("Area of obj1 ="+
class Room
obj1.area());
{ float length;
Room obj2 = new Room(7,5);
float breadth;
System.out.println("Area of obj2 ="+
float area; obj2.area());
Room(float x, float y) }}
{ length = x;
CLASS, OBJECT AND METHOD
public class Main { // Overloaded sum(). This sum takes two
double parameters
// Overloaded sum(). This sum takes two public double sum(double x, double y)
int parameters {
public int sum(int x, int y) return (x + y);
{ }
return (x + y);
} // Driver code
public static void main(String args[])
// Overloaded sum(). This sum takes {
three int parameters Main s = new Main();
public int sum(int x, int y, int z) System.out.println(s.sum(10, 20));
{ System.out.println(s.sum(10, 20, 30));
return (x + y + z); System.out.println(s.sum(10.5, 20.5));
} }
}
CLASS, OBJECT AND METHOD
Method Overloading class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return
Methods have the same name but
a+b+c;}
different parameter list and different
definitions. }
Used when objects are required to class TestOverloading1{
perform similar tasks but using public static void main(String[] args){
different input parameters. System.out.println(Adder.add(11,11));
Ex of polymorphism System.out.println(Adder.add(11,11,11));

}}
CLASS, OBJECT AND METHOD
Static Members
rollno = r;
name = n;
If the members (variables or functions )
have to be common between the }
objects, then they have to be declared void display ()
as Static {System.out.println(rollno+"
Ex: Static Variable "+name+" "+college);}
public static void main(String args[]){
Student8 s1 = new
class Student8{
Student8(111,"Karan");
int rollno;
Student8 s2 = new
String name; Student8(222,"Aryan");
static String college ="ITS"; s1.display();
s2.display();
Student8(int r,String n){ } }
class Main
{ static int count=0;
public void increment()
{ count++;
}
public static void main(String args[])
{ Main obj1 = new Main();
Main obj2 = new Main();
obj1.increment();
obj2.increment();
System.out.println("Obj1: count is="+obj1.count);
System.out.println("Obj2: count is="+obj2.count);
}
}
* Remove static keyword and see the difference also.
CLASS, OBJECT AND METHOD
Static Method Student9(int r, String n){
 If you apply static keyword with any rollno = r;
method, it is known as static method. name = n;
}
 A static method belongs to the class rather
than object of a class. void display ()
 A static method can be invoked without {System.out.println(rollno+" "+name+" "+college);}
the need for creating an instance of a public static void main(String args[]){
class. Student9.change();
Student9 s1 = new Student9 (111,"Karan");
 static method can access static data
Student9 s2 = new Student9 (222,"Aryan");
member and can change the value of it.
Student9 s3 = new Student9 (333,"Sonoo");
class Student9{
s1.display();
int rollno;
s2.display();
String name;
s3.display();
static String college = "ITS";
}
}
static void change(){
college = "BBDIT";
}
class Main{
int rollno; void display ()
String name; {System.out.println(rollno+" "+name+"
static int count =0; "+college+ " " +count);}
static String college = "ITS"; public static void main(String args[]){
Main.change();
static void change(){ Main s1 = new Main (111,"Karan");
college = "BBDIT"; Main s2 = new Main (222,"Aryan");
} Main s3 = new Main (333,"Sonoo");
s1.display();
Main(int r, String n){ s2.display();
rollno = r; s3.display();
name = n; }
} }
CLASS, OBJECT AND METHOD
Static Method Student9(int r, String n){
 If you apply static keyword with any rollno = r;
method, it is known as static method. name = n;
}
 A static method belongs to the class rather
than object of a class. void display ()
 A static method can be invoked without {System.out.println(rollno+" "+name+" "+college);}
the need for creating an instance of a public static void main(String args[]){
class. Student9.change();
Student9 s1 = new Student9 (111,"Karan");
 static method can access static data
Student9 s2 = new Student9 (222,"Aryan");
member and can change the value of it.
Student9 s3 = new Student9 (333,"Sonoo");
class Student9{
s1.display();
int rollno;
s2.display();
String name;
s3.display();
static String college = "ITS";
}
}
static void change(){
college = "BBDIT";
}
CLASS, OBJECT AND METHOD
z = x - y;
Inheritance System.out.println("The difference between the given
Inheritance can be defined as the process where one numbers:"+z);
}
class acquires the properties (methods and
}
fields) of another.
The class which inherits the properties of other is public class My_Calculation extends Calculation {
known as subclass (derived class, child class) public void multiplication(int x, int y) {
and the class whose properties are inherited is z = x * y;
known as superclass (base class, parent class). System.out.println("The product of the given numbers:"+z);
}
extends is the keyword used to inherit the
properties of a class. Following is the syntax of public static void main(String args[]) {
extends keyword. int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
class Calculation { demo.Subtraction(a, b);
int z; demo.multiplication(a, b);
}
public void addition(int x, int y) { }
z = x + y;
System.out.println("The sum of the given numbers:"+z);
}

public void Subtraction(int x, int y) {


CLASS, OBJECT AND METHOD
class Teacher {
String designation = "Teacher";
String college ="AJCE";
void does(){
System.out.println("Teaching");
}
}
public class MathTeacher extends Teacher{  AJCE
String mainSubject = "Maths";  Teacher
public static void main(String args[]){  Maths
MathTeacher obj = new  Teaching
MathTeacher();
System.out.println(obj.college);
System.out.println(obj.designation);
System.out.println(obj.mainSubject);
obj.does();
}
}
Inheritance
CLASS, OBJECT AND METHOD
Method Overriding
 Overriding is a feature that allows a
 Method overriding is one of the way by
subclass or child class to provide a which java achieve 
specific implementation of a method that Run Time Polymorphism.
is already provided by one of its super-  If an object of a parent class is used to
classes or parent classes. invoke the method, then the version in the
 When a method in a subclass has the same parent class will be executed, but if an
name, same parameters or signature and object of the subclass is used to invoke
same return type(or sub-type) as a method the method, then the version in the child
in its super-class, then the method in the class will be executed. In other words, it
subclass is said to override the method in is the type of the object being referred to
the super-class. that determines which version of an
overridden method will be executed.
 The benefit of overriding is: ability to
define a behavior that's specific to the
subclass type, which means a subclass can
implement a parent class method based on
its requirement.
CLASS, OBJECT AND METHOD
class Animal { b.move(); // runs the method in Dog
public void move() { class
System.out.println("Animals can move"); }
}} }
 In the above example, you can see that even
class Dog extends Animal { though b is a type of Animal it runs the move method
public void move() { in the Dog class. The reason for this is: In compile
time, the check is made on the reference type.
System.out.println("Dogs can walk and However, in the runtime, JVM figures out the object
run"); type and would run the method that belongs to that
}} particular object.
 Therefore, in the above example, the program will
public class TestDog { compile properly since Animal class has the method
public static void main(String args[]) { move. Then, at the runtime, it runs the method
specific for that object.
Animal a = new Animal(); // Animal
reference and object Animals can move
Animal b = new Dog(); // Animal
 Dogs can walk and run
reference but Dog object
a.move(); // runs the method in Animal
//class
class Animal { }}
Animal() public class TestDog {
{System.out.println("Animal constructor"); public static void main(String args[]) {
} // Animal a = new Animal(); // Animal
public void move() { reference and object
System.out.println("Animals can move"); // Animal b = new Dog(); // Animal
}} reference but Dog object
class Dog extends Animal { // Dog c = new Dog();
Dog() // Dog d = new Animal();
{System.out.println("Dog constructor"); // a.move(); // runs the method in Animal
class
}
// b.move(); // runs the method in Dog class
public void move() {
d.move();
System.out.println("Dogs can walk and
run"); }
}
CLASS, OBJECT AND METHOD
 Abstract Class and that contains one or more
methods abstract methods.
abstract class A{
 Abstract method - A abstract void myMethod();
void anotherMethod(){
method that is declared but //Does something
}
not defined. Only method }
signature no body.  We cannot create an object
abstract public void for an abstract class.
playInstrument();
 The class that inherits must
provide the implementation
of all the abstract methods
of parent class 
 Abstract Class – a class
CLASS, OBJECT AND METHOD
 Final Keyword in Java
 final keyword is used in different contexts. First of all, final is a 
non-access modifier applicable only to a variable, a method or a
class. Following are different contexts where final is used.

 https://www.javatpoint.com/final-keyword
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
System.out.println(speedlimit);
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}
Check the same program by removing final keyword
public class Bike9{
int speedlimit=90;//final variable
void run(){
speedlimit=400;
System.out.println(speedlimit);
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}
class Bike{
final void run(){System.out.println("running");}
}

class Honda extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda honda= new Honda();
honda.run();
}
}
class Bike{
void run(){System.out.println("running");}
}

public class Honda extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String[] args){


Honda honda= new Honda();
honda.run();
}
}
class Bike{}

class Honda1 extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda1 honda= new Honda1();
honda.run();
}
}
final class Bike{}

public class Honda1 extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda1 honda= new Honda1();
honda.run();
}
}
INTERFACE
It is a kind of class.
Interface contains methods and Ex:
variables but with a major Interface Area
difference. { final static float pi=3.14;
It defines only abstract methods float compute(float x, float y);
and final and static fields.
void show();
Syntax:
}
interface interfacename
{ variables declaration;
Methods declaration;
}
 Why Multiple Inheritance is not supported?
Is it linked to virtual class concept?

Why are we using abstraction? What is its


importance?
INTERFACE
interface vehicleone{ }
int speed=90; }
public void distance();}
interface vehicletwo{ class MultipleInheritanceUsingInterface{
int distance=100; public static void main(String args[]){
public void speed();} System.out.println("Vehicle");
class Vehicle implements Vehicle obj = new Vehicle();
vehicleone,vehicletwo{ obj.distance();
public void distance(){ obj.speed();
int distance=speed*100; }
System.out.println("distance travelled }
is "+distance);
}
public void speed(){
int speed=distance/100;
INTERFACE
class student //program in java to show multiple public void putwt()
inheritance {System.out.println("Sports Marks "+ sportwt);}
{ int rollNumber; void display()
void getNumber(int n) {total=part1+part2+sportwt;
{ rollNumber=n;} System.out.println("Total marks of " +rollNumber+" is
void printNumber() "+total);
{System.out.println("RollNo is " +rollNumber);}} }}
class mainClass
class test extends student {public static void main(String srgs[])
{float part1,part2; {results a=new results();
void getMarks(float a, float b) a.getNumber(10);
{part1=a; a.printNumber();
part2=b;} a.getMarks(10.0F,25.5F);
void putMarks() a.putMarks();
{System.out.println("Marks Part1 "+part1); a.putwt();
System.out.println("Marks Part2 "+part2);}} a.display();
interface sports }}
{float sportwt=6.0F;
void putwt();}
class results extends test implements sports
{float total;

You might also like