This website is for sell contact:- +919827974760 Java Types of Modifiers Tutorial with Example
  • Struts
  • PHP
  • jQuery
  • SQL Tutorial
  • Spring
  • JavaScript
  • JSP
  • RubyonRails
  • Core Java

  • <

    Java Modifiers Tutorial

    There are 2 types of Modifier in java . Java access modifier and Non access modifier


    There are 4 types of java access modifiers




    Non access modifiers are static, abstract, volatile, transient etc..


    Java private access modifier Example



    Hen class
    package bird;
     
    public class Hen {
     
        private String rice;
     
        public Hen() {
            rice = "eat";
        }
    }
    

    Fly class
    package flying;
     
    import bird.Hen;
     
    public class Fly {
        public void top(Hen hen) {
            hen.rice = "fly"; // COMPILE ERROR
    } }

    Error because accessing private members outside the class.


    Java default access modifier Example


    Wolf class
     package animal;
     
    class Wolf {
        public void play() {
         }
    }
    

    Person class

    package human;
     
    import animal.Wolf;
     
    public class Person {
        public void hunt() {
            Wolf wolf = new Wolf(); // COMPILE ERROR
        }
    } 
    


    Error because the Wolf class has default accessibility


    Java protected access modifier Example


    Person class

    package human;
     
    import animal.Dog;
     
    public class Person {
        public void play() {
            Dog dog = new Dog();
            dog.waveTail(); // COMPILE ERROR!
        }
    }
    

    Dog class

    package animal;
     
    public class Dog {
        protected void waveTail() {
            System.out.print("Waving my tail...");
        }
    }
    

    waveTail() has protected access in Dog


    Java public access modifier



    Dog class
    package animal;
     
    public class Dog {
        public String name;
     
        public void bark() {
            System.out.print("Gow Gow!");
        }
    }
    

    Trainer class
    package training;
    
    import animal.Dog;
    
    public class Trainer {
    public void teach(Dog dog) {
    
    dog.name = "Rex";
    dog.bark();
    }
    }
    

    Here, the Dog and Trainer classes are in 2 different packages: animal and training, respectively. Because the Dog class is declared as public, and also its member name field and bark() method, the Trainer class can invoke them:













    © copyright 2017-2022 Completedone pvt ltd.